Skip to content

Python Variable Types

Variables are fundamental concepts in programming, acting as named containers for storing data values in memory. When you create a variable in Python, you reserve memory space for the data it will hold.

Python is dynamically typed, meaning you don’t need to explicitly declare the type of a variable beforehand. The interpreter automatically determines the type based on the value assigned to it.

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

# Variable assignments
counter = 100 # An integer assignment
pi_value = 3.14159 # A floating-point assignment
name = "Alice" # A string assignment
is_active = True # A boolean assignment
my_list = [1, 2, 3] # A list assignment
# Using the variables
print(counter)
print(pi_value)
print(name)
print(is_active)
print(my_list)

Output:

100
3.14159
Alice
True
[1, 2, 3]

Python allows assigning a single value to multiple variables simultaneously:

x = y = z = 0 # All three variables reference the same integer object 0
print(x, y, z)

You can also assign multiple distinct values to multiple variables in one line (often used for unpacking sequences):

a, b, city = 1, 2.5, "New York"
print(a) # Output: 1
print(b) # Output: 2.5
print(city) # Output: New York

Python has several built-in data types that define the kind of data a variable can hold and the operations that can be performed on it. Key standard types include:

  • Numeric Types: int, float, complex
  • Sequence Types: str, list, tuple
  • Mapping Type: dict
  • Set Types: set, frozenset
  • Boolean Type: bool
  • Binary Types: bytes, bytearray, memoryview
  • None Type: NoneType (has only one value: None)

Store numeric values. They are immutable.

int_var = 10
float_var = 12.5
complex_var = 3 + 4j
# Deleting variable references
del float_var
# print(float_var) # Would raise NameError

Represent ordered collections of items.

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 (Slice from index 6 up to 11)
print(my_str[6:]) # Output: World! (Slice from index 6 to end)
print(my_str * 2) # Output: Hello World!Hello World!
print(my_str + " Python") # Output: Hello World! Python
my_list = ['abcd', 786, 2.23, 'john', 70.2]
tiny_list = [123, 'john']
print(my_list) # Output: ['abcd', 786, 2.23, 'john', 70.2]
print(my_list[0]) # Output: abcd
print(my_list[1:3]) # Output: [786, 2.23]
print(my_list[2:]) # Output: [2.23, 'john', 70.2]
print(tiny_list * 2) # Output: [123, 'john', 123, 'john']
print(my_list + tiny_list) # Output: ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
# Lists are mutable
my_list[2] = 'updated'
print(my_list) # Output: ['abcd', 786, 'updated', 'john', 70.2]
my_tuple = ('abcd', 786, 2.23, 'john', 70.2)
tiny_tuple = (123, 'john')
print(my_tuple) # Output: ('abcd', 786, 2.23, 'john', 70.2)
print(my_tuple[0]) # Output: abcd
print(my_tuple[1:3]) # Output: (786, 2.23)
print(my_tuple[2:]) # Output: (2.23, 'john', 70.2)
print(tiny_tuple * 2) # Output: (123, 'john', 123, 'john')
print(my_tuple + tiny_tuple) # Output: ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
# Tuples are immutable
# my_tuple[2] = 1000 # This would raise a TypeError

dict (Dictionary): Mutable collection of unique key-value pairs. Defined using curly braces {}. Keys must be immutable types (like strings, numbers, tuples). Values can be any type. Dictionaries are unordered in older Python versions but maintain insertion order in Python 3.7+.

my_dict = {}
dict_one = {'name': 'john', 'code': 6734, 'dept': 'sales'}
my_dict['one'] = "This is value one"
my_dict[2] = "This is value two"
print(my_dict['one']) # Output: This is value one
print(my_dict[2]) # Output: This is value two
print(dict_one) # Output: {'name': 'john', 'code': 6734, 'dept': 'sales'}
print(dict_one.keys()) # Output: dict_keys(['name', 'code', 'dept'])
print(dict_one.values()) # Output: dict_values(['john', 6734, 'sales'])

Represent unordered collections of unique, immutable items. Used for membership testing, removing duplicates, and set operations (union, intersection, etc.).

my_set = {1, 2, 3, 2, 1} # Duplicates are automatically removed
print(my_set) # Output: {1, 2, 3} (Order may vary)
empty_set = set()
print(empty_set) # Output: set()
frozen = frozenset(["a", "b", "c"])
print(frozen) # Output: frozenset({'c', 'a', 'b'})
# frozen.add("d") # AttributeError: 'frozenset' object has no attribute 'add'

Represents truth values. Has only two possible values: True and False (note capitalization). Often the result of comparisons or logical operations.

is_valid = True
has_error = False
print(is_valid) # Output: True
print(5 > 3) # Output: True
print(type(False)) # Output: <class 'bool'>

Represents the absence of a value. Has only one value: None. Often used as a default or placeholder.

result = None
print(result) # Output: None
print(type(None)) # Output: <class 'NoneType'>

You can often convert between data types using built-in functions named after the target type.

FunctionDescription
int(x [,base])Converts x to an integer. base specifies the base if x is a string (e.g., int('101', 2)).
float(x)Converts x to a floating-point number.
str(x)Converts object x to a string representation.
list(s)Converts iterable s to a list.
tuple(s)Converts iterable s to a tuple.
set(s)Converts iterable s to a set.
dict(d)Creates a dictionary. d can be a sequence of (key, value) pairs or keyword arguments.
bool(x)Converts x to a boolean. False for 0, None, empty sequences/mappings; True otherwise.
complex(real [,imag])Creates a complex number.
bytes(source [, encoding])Creates an immutable bytes object.
chr(i)Converts an integer i to its corresponding Unicode character.
ord(c)Converts a single character c to its integer Unicode code point.
hex(x)Converts an integer to a lowercase hexadecimal string prefixed with “0x”.
oct(x)Converts an integer to an octal string prefixed with “0o”.

Note: The long() function from Python 2 is removed; int handles arbitrary size. eval() evaluates a string as Python code, use with extreme caution due to security risks. repr() gives an unambiguous string representation, often usable to recreate the object.