Python has a rich set of built-in data types that allow you to store and manipulate data in various ways. Here is a detailed overview of Python’s primary data types:
1. Numeric Types
Integers (int
): Whole numbers, positive or negative, without a fractional part
x = 5
y = -10
Floating-Point Numbers (float
): Numbers with a fractional part.
pi = 3.14159
e = 2.718
Complex Numbers (complex
): Numbers with a real and an imaginary part.
z = 3 + 4j
w = 5 - 2j
2. Sequence Types
Strings (str
): Ordered sequences of characters.
name = "Alice"
greeting = 'Hello, World!'
Lists (list
): Ordered, mutable collections of items.
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
Tuples (tuple
): Ordered, immutable collections of items.
coordinates = (10.0, 20.0)
colors = ('red', 'green', 'blue')
Ranges (range
): Immutable sequences of numbers, commonly used for looping a specific number of times in for loops.
r = range(5) # 0, 1, 2, 3, 4
3. Mapping Types
Dictionaries (dict
): Unordered collections of key-value pairs
person = {"name": "John", "age": 30, "city": "New York"}
scores = {"Alice": 90, "Bob": 85}
4. Set Types
Sets (set
): Unordered collections of unique items
unique_numbers = {1, 2, 3, 4, 5}
Frozen Sets (frozenset
): Immutable sets.
frozen_set = frozenset([1, 2, 3, 4, 5])
5. Boolean Type
Booleans (bool
): Represent True
or False
values.
is_active = True
is_closed = False
6. Binary Types
Bytes (bytes
): Immutable sequences of bytes.
b = b'Hello'
Byte Arrays (bytearray
): Mutable sequences of bytes.
ba = bytearray(b'Hello')
Memory Views (memoryview
): Provides a view of another binary sequence without copying it.
mv = memoryview(bytes(5))
7. None Type
NoneType (None
): Represents the absence of a value.
result = None
Examples of Data Type Usage
# Numeric Types
age = 25 # int
height = 5.9 # float
complex_num = 3 + 2j # complex
# Sequence Types
name = "John Doe" # str
numbers = [1, 2, 3, 4, 5] # list
coordinates = (10.0, 20.0) # tuple
range_numbers = range(5) # range
# Mapping Type
person = {"name": "Alice", "age": 28} # dict
# Set Types
unique_ids = {101, 102, 103} # set
immutable_ids = frozenset([101, 102, 103]) # frozenset
# Boolean Type
is_student = True # bool
# Binary Types
byte_seq = b'Hello' # bytes
mutable_byte_seq = bytearray(b'Hello') # bytearray
memory_view_seq = memoryview(bytes(5)) # memoryview
# None Type
nothing = None # NoneType