Fundamental Data Types
Python offers many built-in data types, each designed to handle specific kinds of data:
1. Numeric Types:
These types represent numbers in various forms:
int
(Integers): Whole numbers without decimal points.
= 10
x = -5
y print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'int'>
float
(Floating-Point Numbers): Numbers with decimal points.
= 3.14
a = -2.5
b print(type(a)) # Output: <class 'float'>
print(type(b)) # Output: <class 'float'>
complex
(Complex Numbers): Numbers with a real and an imaginary part (e.g., 2+3j).
= 2 + 3j
c print(type(c)) # Output: <class 'complex'>
2. Text Type:
str
(Strings): Sequences of characters enclosed in single (’ ’) or double (” “) quotes.
= "Python"
name = 'Hello, world!'
message print(type(name)) # Output: <class 'str'>
print(type(message)) # Output: <class 'str'>
3. Sequence Types:
These types represent ordered collections of items:
list
(Lists): Ordered, mutable (changeable) sequences of items. Items can be of different data types.
= [1, "hello", 3.14, True]
my_list print(type(my_list)) # Output: <class 'list'>
0] = 10 # Modifying a list element
my_list[print(my_list) # Output: [10, 'hello', 3.14, True]
tuple
(Tuples): Ordered, immutable (unchangeable) sequences of items.
= (1, "hello", 3.14, True)
my_tuple print(type(my_tuple)) # Output: <class 'tuple'>
range
(Ranges): Represents a sequence of numbers. Often used in loops.
= range(1, 6) # Creates a sequence from 1 to 5
numbers print(list(numbers)) # Output: [1, 2, 3, 4, 5]
print(type(numbers)) # Output: <class 'range'>
4. Mapping Type:
dict
(Dictionaries): Unordered collections of key-value pairs. Keys must be immutable (e.g., strings, numbers, tuples).
= {"name": "Alice", "age": 30, "city": "New York"}
my_dict print(type(my_dict)) # Output: <class 'dict'>
print(my_dict["name"]) # Output: Alice
5. Set Types:
set
(Sets): Unordered collections of unique items.
= {1, 2, 2, 3, 4} # Duplicates are automatically removed
my_set print(type(my_set)) # Output: <class 'set'>
print(my_set) # Output: {1, 2, 3, 4}
frozenset
(Frozen Sets): Immutable versions of sets.
6. Boolean Type:
bool
(Booleans): Represents truth values:True
orFalse
.
= True
is_adult = False
is_minor print(type(is_adult)) # Output: <class 'bool'>
7. Binary Types:
bytes
: Sequence of bytes.bytearray
: Mutable sequence of bytes.memoryview
: Allows access to the internal data of an object without copying.
These data types form the foundation of Python programming. Choosing the appropriate data type ensures efficient and correct code execution. Further exploration into more advanced data structures and their applications will significantly improve your Python programming skills.