A comprehensive guide to Python’s built-in data structures.
Lists
Lists are mutable sequences in Python:
1 2 3 4 5 6 7 8 9 10 11 12
| fruits = ['apple', 'banana', 'cherry'] numbers = [1, 2, 3, 4, 5]
fruits.append('orange') fruits.extend(['grape', 'mango']) first_fruit = fruits[0] last_fruit = fruits[-1]
squares = [x**2 for x in range(10)]
|
Dictionaries
Dictionaries store key-value pairs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| person = { 'name': 'Alice', 'age': 30, 'city': 'New York' }
name = person['name'] age = person.get('age', 0)
keys = person.keys() values = person.values() items = person.items()
|
Sets
Sets are unordered collections of unique elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| colors = {'red', 'green', 'blue'} numbers = set([1, 2, 2, 3, 3, 4])
colors.add('yellow') colors.remove('red') is_member = 'blue' in colors
set1 = {1, 2, 3} set2 = {3, 4, 5} union = set1 | set2 intersection = set1 & set2 difference = set1 - set2
|
Tuples
Tuples are immutable sequences:
1 2 3 4 5 6 7 8 9 10 11 12 13
| coordinates = (10, 20) rgb = (255, 128, 0)
x, y = coordinates r, g, b = rgb
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(10, 20) print(p.x, p.y)
|
These data structures form the foundation of Python programming!