Python Data Types
Data Types in Python
Python provides a variety of data types to handle different types of information, from simple numbers and text to more complex data structures. These types form the foundation of Python's flexible and dynamic programming model. For example, integers represent whole numbers like `-3` and `10`, floating-point numbers handle decimals like `-1.345` or `2.314`, and strings deal with text such as `'hello'` or `'48 students'`. Each data type has specific characteristics that make it suitable for particular tasks.
Variables and Data Types
Python supports numerous data types for handling various forms of data. Below is a table summarizing common types and their usage:
Usage | Data Type | Example |
---|---|---|
Text | str | `"sandworm"` |
Numeric | int, float, complex | `20, 1.2, 1+1j` |
Sequence | list | `["matrix", "dune"]` |
tuple | `("x", "y")` | |
range | `range(6)` | |
Mapping | dict | `{"name": "Paul", "age": 36}` |
Set | set | `{"matrix", "dune"}` |
frozenset | `frozenset({"air", "tree"})` | |
Boolean | bool | `True, False` |
Binary | bytes, bytearray | |
memoryview | ||
None | NoneType | `None` |
These types allow Python to efficiently manage a wide range of data formats.
Variables
In Python, variables are dynamically typed, meaning you donβt need to explicitly define their type. Python infers the type based on the value assigned. For instance:
x = 10
y = 'Ten'
z = {'Hydrogen': 'H', 'Carbon': 'C'}
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>
print(type(z)) # <class 'dict'>
This flexibility simplifies programming and reduces boilerplate code.
Enforcing Data Types
Although Python is dynamically typed, you can enforce specific data types when needed. This is particularly useful for ensuring data consistency:
x = 5
y = "Hello, World!"
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>
x = float(1)
print(type(x)) # <class 'float'>
x = complex(1)
print(type(x)) # <class 'complex'>
Collection of Data: List
A list is an ordered, mutable collection of items. Lists can contain duplicate elements and support a variety of data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
list4 = ["abc", 34, True, 40, "matrix"]
print(len(list4)) # 5
print(list1[0]) # "apple"
list1[0] = "blueberry"
print(list1) # ["blueberry", "banana", "cherry"]
Collection of Data: Tuple
A tuple is an immutable, ordered collection. Once created, its size and content cannot be changed. For example:
tuple1 = ("apple", "banana", "cherry")
print(tuple1[0]) # "apple"
tuple1[0] = "blueberry" # Error: Tuples are immutable
Tuples are ideal for storing fixed collections, such as coordinates.
List vs Tuple
Lists are mutable, while tuples are immutable. This distinction can affect behavior, especially when variables are passed by reference:
a = [100, 2]
b = a
a[0] = 10
print(a, b) # [10, 2], [10, 2]
Versus:
a = (100, 2)
b = a
a = (10, 2)
print(a, b) # (10, 2), (100, 2)
Variable Name as a Reference in Functions
When you pass a mutable data type, like a list, to a function, changes inside the function affect the original variable:
def myFun(x):
x[0] = 20
lst = [10, 11, 12]
myFun(lst)
print(lst) # [20, 11, 12]
Collection of Data: Set
A set is an unordered collection of unique elements. Sets do not allow duplicates and are useful for operations like union and intersection:
set1 = {"apple", "banana", "cherry"}
set5 = {"abc", 34, True, 34, "matrix"}
print(set5) # {"abc", 34, True, "matrix"}
Collection of Data: Dictionary
A dictionary is a collection of key-value pairs. Each key must be unique, and the values can be updated or retrieved using the keys:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car["brand"]) # "Ford"
car["year"] = 2023
print(car) # {"brand": "Ford", "model": "Mustang", "year": 2023}
Collection of Data: List, Tuple, Set, Dict
Here is a summary of the differences between these collections:
Property | List | Tuple | Set | Dict |
---|---|---|---|---|
Ordered | Yes | Yes | No | Yes |
Changeable | Yes | No | No | Yes |
Allows Duplicates | Yes | Yes | No | No |
The None Data Type
The `None` type represents the absence of a value. It is often used as a placeholder or a return value when no other value is available:
import re
matched = re.match("a", "a tiger")
print(matched) # <re.Match object; span=(0, 1), match='a'>
matched = re.match("Paul Atreides", "ME 480 Student List")
if matched is None:
print("It doesn't match.")