What are Python’s built-in data types?
26/06/2024Python offers a variety of built-in data types that are designed to handle different kinds of data efficiently.
Numeric Types:
- int (Integer):
- Represents whole numbers without a fractional component.
- Example: a = 10
- float (Floating Point):
- Represents real numbers with a fractional component.
- Example: b = 10.5
- complex (Complex Number):
- Represents complex numbers with a real and an imaginary part.
- Example: c = 3 + 4j
Sequence Types:
- str (String):
- Represents a sequence of characters (text).
- Example: s = “Hello”
- list (List):
- Represents an ordered collection of items, which can be of mixed types.
- Example: l = [1, 2, 3, “four”]
- tuple (Tuple):
- Represents an ordered collection of items, which can be of mixed types.
- Example: t = (1, 2, 3, “four”)
- range:
- Represents an immutable sequence of numbers, commonly used for looping a specific number of times in for loops.
- Example: r = range(5)
Mapping Type:
- dict (Dictionary):
- Represents a collection of key-value pairs.
- Example: d = {“key1”: “value1”, “key2”: “value2”}
Set Types:
- set:
- Represents an unordered collection of unique items.
- Example: s = {1, 2, 3, 4}
- frozenset:
- Represents an immutable version of a set.
- Example: fs = frozenset([1, 2, 3, 4])
Boolean Type:
- bool:
- Represents Boolean values: True and False.
- Example: flag = True
Binary Types:
- bytes:
- Represents an immutable sequence of bytes.
- Example: b = b’hello’
- bytearray:
- Represents a mutable sequence of bytes.
- Example: ba = bytearray(b’hello’)
- memoryview:
- Represents a view object that exposes the memory of another binary object (like bytes or bytearray) without copying.
- Example: mv = memoryview(b’hello’)
None Type:
- NoneType:
- Represents the absence of a value or a null value.
- Example: n = None
Examples and Usage:
Numeric Types:
a = 10 # int
b = 10.5 # float
c = 3 + 4j # complex
Sequence Types:
s = “Hello” # str
l = [1, 2, 3, “four”] # list
t = (1, 2, 3, “four”) # tuple
r = range(5) # range
Mapping Type:
d = {“key1”: “value1”, “key2”: “value2”} # dict
Set Types:
s = {1, 2, 3, 4} # set
fs = frozenset([1, 2, 3, 4]) # frozenset
Boolean Type:
flag = True # bool
Binary Types:
b = b’hello’ # bytes
ba = bytearray(b’hello’) # bytearray
mv = memoryview(b’hello’) # memoryview
None Type:
n = None # NoneType