Python Data Types
Python Data Types
Python provides a variety of built-in data types to handle different kinds of data. These include:
- Numbers: int, float, complex
- Strings: text sequences
- Collections: list, tuple, dict, set
Numbers
Numeric types support arithmetic operations:
# Integer x = 42 # Float y = 3.14 # Complex z = 1 + 2j # Operations sum_val = x + y # 45.14 product = x * 2 # 84 magnitude = abs(z) # sqrt(1^2 + 2^2)
Strings
Strings are immutable sequences. Common operations:
s = "Hello, World!" # Length and indexing length = len(s) first = s[0] # 'H' # Slicing sub = s[7:12] # 'World' # Methods upper = s.upper() # 'HELLO, WORLD!' contains = "World" in s # True # f-strings for formatting name = "Alice" greeting = f"Welcome, {name}!"
Lists, Tuples, Dicts
List (mutable)
items = [1, 2, 3] items.append(4) items[0] = 0 # [0, 2, 3, 4]
Tuple (immutable)
coords = (10.0, 20.0) # coords[0] = 5.0 # raises TypeError
Dict (key-value)
config = {"debug": True, "timeout": 30} value = config.get("timeout") # 30 for key, val in config.items(): print(key, val)