Skip to content

Python 3 - Variable Types

In Python, variables are essentially names or labels that refer to values stored in the computer’s memory. When you create a variable, you are associating a name with a specific piece of data (an object).

Python uses dynamic typing, meaning you don’t need to explicitly declare the data type of a variable beforehand. The type is inferred automatically when you assign a value to it.

Use the assignment operator (=) to assign a value to a variable name. The name goes on the left, the value on the right.

#!/usr/bin/env python3
count = 100 # Integer assignment
pi_approx = 3.14159 # Floating-point assignment
message = "Hello" # String assignment
is_active = True # Boolean assignment
print(count)
print(pi_approx)
print(message)
print(is_active)

Output:

100
3.14159
Hello
True

Python allows assigning the same value to multiple variables simultaneously:

x = y = z = 0 # All three variables now refer to the integer 0
print(x, y, z)

You can also assign multiple different values to multiple variables in one line (sequence unpacking):

a, b, c = 1, 2.5, "world" # a=1, b=2.5, c="world"
print(a, b, c)

Python has several fundamental data types built-in:

  • Numeric Types: int, float, complex
  • Sequence Types: str (String), list, tuple, range
  • Mapping Type: dict (Dictionary)
  • Set Types: set, frozenset
  • Boolean Type: bool (True and False)
  • Binary Types: bytes, bytearray, memoryview
  • None Type: NoneType (represents the absence of a value, has only one value: None)

Let’s look closer at the most common ones.

Covered in detail in the ‘Numbers’ chapter. Key points:

  • int: Arbitrary precision whole numbers.
  • float: Double-precision floating-point numbers (can have inaccuracies).
  • complex: Numbers with real and imaginary parts (a + bj).
integer_num = -50
float_num = 1.618
complex_num = 2 - 3j

Strings represent sequences of Unicode characters. They are immutable (cannot be changed after creation).

Defined using single ('...'), double ("..."), or triple ('''...''' or """...""") quotes. Support indexing, slicing, concatenation (+), and repetition (*).

#!/usr/bin/env python3
my_str = 'Hello World!'
print(my_str) # Output: Hello World!
print(my_str[0]) # Output: H (first character)
print(my_str[6:11]) # Output: World (slicing)
print(my_str[6:]) # Output: World! (slice to the end)
print(my_str * 2) # Output: Hello World!Hello World!
print(my_str + " Goodbye!") # Output: Hello World! Goodbye!
# Immutability example:
# my_str[0] = 'J' # TypeError: 'str' object does not support item assignment
# Formatted strings (f-strings - Python 3.6+ are recommended)
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}") # Output: Name: Alice, Age: 30

Lists are ordered, mutable (changeable) sequences of items, enclosed in square brackets []. Items can be of different data types.

Support indexing, slicing, concatenation (+), repetition (*), and have methods for adding (append, insert), removing (remove, pop), sorting (sort), etc.

#!/usr/bin/env python3
my_list = ['abcd', 786, 2.23, 'john', 70.2, True]
tiny_list = [123, 'john']
print(my_list) # Prints complete list
print(my_list[0]) # Prints first element: abcd
print(my_list[1:3]) # Prints elements from index 1 to 2: [786, 2.23]
print(my_list[2:]) # Prints elements from index 2 to end
print(tiny_list * 2) # Prints list repeated: [123, 'john', 123, 'john']
print(my_list + tiny_list) # Prints concatenated list
# Mutability example:
my_list[2] = 'updated'
my_list.append(False)
print(f"Modified list: {my_list}")

Tuples are ordered, immutable sequences of items, usually enclosed in parentheses (). Often used for fixed collections or where immutability is required (e.g., dictionary keys).

Support indexing, slicing, concatenation (+), repetition (*). Cannot be changed after creation.

#!/usr/bin/env python3
my_tuple = ('abcd', 786, 2.23, 'john', 70.2)
tiny_tuple = (123, 'john')
print(my_tuple) # Prints complete tuple
print(my_tuple[0]) # Prints first element: abcd
print(my_tuple[1:3]) # Prints elements from index 1 to 2: (786, 2.23)
print(my_tuple[2:]) # Prints elements from index 2 to end
print(tiny_tuple * 2) # Prints tuple repeated: (123, 'john', 123, 'john')
print(my_tuple + tiny_tuple) # Prints concatenated tuple
# Immutability example:
# my_tuple[2] = 1000 # TypeError: 'tuple' object does not support item assignment

Dictionaries store unordered (in Python < 3.7) or insertion-ordered (Python 3.7+) collections of key-value pairs. Enclosed in curly braces {}.

Keys must be unique and immutable (hashable). Values can be any type. Accessed via keys using square brackets [] or the .get() method.

#!/usr/bin/env python3
my_dict = {}
my_dict['one'] = "This is value one"
my_dict[2] = "This is value two"
tiny_dict = {'name': 'john', 'code': 6734, 'dept': 'sales'}
print(my_dict['one']) # Access value using key 'one'
print(my_dict[2]) # Access value using key 2
print(tiny_dict) # Prints complete dictionary
print(tiny_dict.keys()) # Prints view object of keys
print(tiny_dict.values()) # Prints view object of values
print(tiny_dict.items()) # Prints view object of (key, value) pairs
# Modifying dictionary
tiny_dict['dept'] = 'marketing'
tiny_dict['city'] = 'New York'
print(f"Updated tiny_dict: {tiny_dict}")

set: Unordered collections of unique, immutable items. Enclosed in curly braces {} (but {} creates an empty dictionary, use set() for an empty set). Useful for membership testing and eliminating duplicates.

frozenset: An immutable version of a set. Can be used as dictionary keys or elements of other sets.

#!/usr/bin/env python3
my_set = {1, 2, 3, 2, 'a'} # Duplicates (2) ignored
print(f"My set: {my_set}") # Output: {1, 2, 3, 'a'} (order may vary)
empty_set = set()
print(f"Empty set: {empty_set}")
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(f"Union: {set1 | set2}") # {1, 2, 3, 4, 5}
print(f"Intersection: {set1 & set2}") # {3}
print(f"Difference: {set1 - set2}") # {1, 2}

Use built-in functions like int(), float(), str(), list(), tuple(), set(), dict() to convert between compatible types.

Example conversions:

FunctionDescription
int(x [,base])Converts x to integer. Base optional for string conversion.
float(x)Converts x to floating-point.
complex(real [,imag])Creates a complex number.
str(x)Converts object x to string.
repr(x)Converts object x to an expression string (often usable by eval).
eval(str)Evaluates a string as Python code. Warning: Use with extreme caution on untrusted input due to security risks.
tuple(s)Converts iterable s to a tuple.
list(s)Converts iterable s to a list.
set(s)Converts iterable s to a set.
dict(d)Creates a dictionary. d must be an iterable of (key, value) pairs.
frozenset(s)Converts iterable s to a frozenset.
chr(x)Converts integer x to its corresponding Unicode character.
ord(c)Converts a single Unicode character c to its integer value.
hex(x)Converts integer x to a lowercase hexadecimal string prefixed with “0x”.
oct(x)Converts integer x to an octal string prefixed with “0o”.
bin(x)Converts integer x to a binary string prefixed with “0b”.