Python Variable Types
Python Variable Types
Section titled “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.
Assigning Values to Variables
Section titled “Assigning Values to Variables”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 assignmentscounter = 100 # An integer assignmentpi_value = 3.14159 # A floating-point assignmentname = "Alice" # A string assignmentis_active = True # A boolean assignmentmy_list = [1, 2, 3] # A list assignment
# Using the variablesprint(counter)print(pi_value)print(name)print(is_active)print(my_list)Output:
1003.14159AliceTrue[1, 2, 3]Multiple Assignment
Section titled “Multiple Assignment”Python allows assigning a single value to multiple variables simultaneously:
x = y = z = 0 # All three variables reference the same integer object 0print(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: 1print(b) # Output: 2.5print(city) # Output: New YorkStandard Data Types
Section titled “Standard Data Types”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)
Numeric Types (int, float, complex)
Section titled “Numeric Types (int, float, complex)”Store numeric values. They are immutable.
int_var = 10float_var = 12.5complex_var = 3 + 4j
# Deleting variable referencesdel float_var# print(float_var) # Would raise NameErrorSequence Types (str, list, tuple)
Section titled “Sequence Types (str, list, tuple)”Represent ordered collections of items.
String Example:
Section titled “String Example:”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! PythonList Example:
Section titled “List Example:”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: abcdprint(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 mutablemy_list[2] = 'updated'print(my_list) # Output: ['abcd', 786, 'updated', 'john', 70.2]Tuple Example:
Section titled “Tuple Example:”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: abcdprint(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 TypeErrorMapping Type (dict)
Section titled “Mapping Type (dict)”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 oneprint(my_dict[2]) # Output: This is value twoprint(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'])Set Types (set, frozenset)
Section titled “Set Types (set, frozenset)”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 removedprint(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'Boolean Type (bool)
Section titled “Boolean Type (bool)”Represents truth values. Has only two possible values: True and False (note capitalization). Often the result of comparisons or logical operations.
is_valid = Truehas_error = Falseprint(is_valid) # Output: Trueprint(5 > 3) # Output: Trueprint(type(False)) # Output: <class 'bool'>None Type (NoneType)
Section titled “None Type (NoneType)”Represents the absence of a value. Has only one value: None. Often used as a default or placeholder.
result = Noneprint(result) # Output: Noneprint(type(None)) # Output: <class 'NoneType'>Data Type Conversion
Section titled “Data Type Conversion”You can often convert between data types using built-in functions named after the target type.
| Function | Description |
|---|---|
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.