Python Lists, Tuples, and Sets
Lists, tuples, and sets are Python’s main sequence and set types. They store collections of items but have different characteristics and use cases. This tutorial shows how to work with each type effectively.
Lists
Lists are ordered, mutable collections that can contain items of different types.
Creating Lists
# Empty list
empty_list = []
# List with items
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed = ["text", 42, True, 3.14]
# Using list() constructor
from_range = list(range(5)) # [0, 1, 2, 3, 4]
from_string = list("hello") # ['h', 'e', 'l', 'l', 'o']Lists can be created in multiple ways. See the list constructor for more options.
Accessing List Items
fruits = ["apple", "banana", "orange", "grape"]
# Indexing
first = fruits[0] # 'apple'
second = fruits[1] # 'banana'
last = fruits[-1] # 'grape'
second_last = fruits[-2] # 'orange'
# Slicing
first_two = fruits[:2] # ['apple', 'banana']
middle = fruits[1:3] # ['banana', 'orange']
every_other = fruits[::2] # ['apple', 'orange']
print(f"First: {first}, Last: {last}")Slicing is powerful for extracting parts of lists. Learn more about sequence slicing.
Modifying Lists
fruits = ["apple", "banana"]
# Adding items
fruits.append("orange") # Add to end
fruits.insert(1, "kiwi") # Insert at index
fruits.extend(["grape", "pear"]) # Add multiple
# Removing items
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove and return last
popped_index = fruits.pop(1) # Remove at index
# Other operations
fruits.reverse() # Reverse in place
fruits.sort() # Sort in place
print(f"Fruits: {fruits}")Lists are mutable, so you can change them after creation. Check list methods for all operations.
List Comprehensions
List comprehensions provide a concise way to create lists.
# Basic comprehension
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix) # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]Comprehensions are more readable than loops for simple operations. See list comprehensions in the tutorial.
Tuples
Tuples are ordered, immutable sequences. Once created, they cannot be changed.
Creating Tuples
# Empty tuple
empty_tuple = ()
# Tuple with items
coordinates = (10, 20)
person = ("Alice", 30, "Engineer")
single_item = (42,) # Note the comma!
# Without parentheses (tuple packing)
point = 5, 10
print(type(point)) # <class 'tuple'>The comma is crucial for single-item tuples. Learn about tuple syntax.
Tuple Operations
point = (10, 20, 30)
# Accessing (same as lists)
x, y, z = point # Unpacking
first = point[0]
slice_tuple = point[1:3] # (20, 30)
# Tuple methods
count_20 = point.count(20) # Count occurrences
index_30 = point.index(30) # Find index
print(f"Unpacked: x={x}, y={y}, z={z}")Tuples support indexing and slicing like lists. See tuple methods for details.
When to Use Tuples
Tuples are ideal for:
- Fixed data that shouldn’t change
- Dictionary keys (lists can’t be keys)
- Returning multiple values from functions
- Unpacking assignments
# Multiple return values
def get_user_info():
return ("Alice", 30, "alice@example.com")
name, age, email = get_user_info()
print(f"Name: {name}, Age: {age}")
# Dictionary keys
locations = {
(40.7128, -74.0060): "New York",
(34.0522, -118.2437): "Los Angeles"
}Tuples work well as immutable collections. Read about tuple use cases.
Sets
Sets are unordered collections of unique items. They don’t allow duplicates.
Creating Sets
# Empty set
empty_set = set()
# Set with items
fruits = {"apple", "banana", "orange"}
numbers = {1, 2, 3, 2, 1} # Duplicates removed
# From other iterables
from_list = set([1, 2, 2, 3])
from_string = set("hello") # {'h', 'e', 'l', 'o'}
print(numbers) # {1, 2, 3}Sets automatically remove duplicates. See set constructor for more.
Set Operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Membership
print(1 in set1) # True
print(5 not in set1) # True
# Adding/removing
set1.add(5)
set1.remove(2) # Raises KeyError if not found
set1.discard(10) # Safe removal (no error)
# Mathematical operations
union = set1 | set2 # {1, 3, 4, 5, 6}
intersection = set1 & set2 # {3, 4, 5}
difference = set1 - set2 # {1}
symmetric_diff = set1 ^ set2 # {1, 6}
print(f"Union: {union}")Sets support mathematical set operations. Explore set operations comprehensively.
Frozensets
Frozensets are immutable sets that can be used as dictionary keys or set elements.
# Create frozenset
frozen = frozenset([1, 2, 3, 2])
print(frozen) # frozenset({1, 2, 3})
# Can be used as dict key
data = {frozen: "some value"}
print(data[frozen]) # "some value"Frozensets are useful when you need immutable sets. See frozenset documentation.
Common Operations
Length and Membership
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
my_set = {7, 8, 9}
print(len(my_list)) # 3
print(len(my_tuple)) # 3
print(len(my_set)) # 3
print(2 in my_list) # True
print(4 in my_tuple) # True
print(10 in my_set) # FalseAll sequences support len() and in operator. Learn about common sequence operations.
Iteration
# All types support iteration
for item in [1, 2, 3]:
print(item)
for item in (4, 5, 6):
print(item)
for item in {7, 8, 9}:
print(item)Iteration works the same way for all collection types. See iteration documentation.
Copying
import copy
original = [1, [2, 3]]
shallow = original.copy() # Shallow copy
deep = copy.deepcopy(original) # Deep copy
original[1][0] = 99
print(shallow) # [1, [99, 3]] - affected by change
print(deep) # [1, [2, 3]] - not affectedCopying is important for mutable objects. Read about copying in the standard library.
Performance Considerations
- Lists: Fast access by index, slow searches
- Sets: Fast membership tests, no duplicates
- Tuples: Slightly faster than lists for iteration
Choose the right type based on your needs. See time complexity for detailed performance info.
Best Practices
- Use lists for ordered collections you need to modify
- Use tuples for fixed data or multiple return values
- Use sets when you need unique items or membership testing
- Consider list comprehensions for simple transformations
External Resources:
Related Tutorials: