Working with Lists
In this chapter, you'll learn how to loop through an entire list using just a few lines of code regardless of how long the list is. Looping allows you to take the same action with every item in a list, whether it's printing out each name in a list of people or performing the same statistical calculation on every element in a list of numbers.
Looping Through Lists
You'll often want to run through all entries in a list, performing the same task with each item. Python's for
loop makes this easy.
Basic For Loop
# Loop through a list
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
Output:
alice
david
carolina
Doing More Work Within a For Loop
# More detailed output in a loop
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f'{magician.title()}, that was a great trick.')
print(f"I can't wait to see your next trick, {magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")
Output:
Alice, that was a great trick.
I can't wait to see your next trick, Alice.
David, that was a great trick.
I can't wait to see your next trick, David.
Carolina, that was a great trick.
I can't wait to see your next trick, Carolina.
Thank you, everyone. That was a great magic show!
Common For Loop Mistakes
Forgetting the Colon
# This will cause a syntax error
magicians = ['alice', 'david', 'carolina']
for magician in magicians # Missing colon
print(magician)
Indentation Errors
# This will cause an indentation error
message = 'Hello'
print(message) # Unexpected indent
Making Numerical Lists
Lists are ideal for storing sets of numbers, and Python provides several tools to help you work with lists of numbers efficiently.
Using the range() Function
Python's range()
function makes it easy to generate a series of numbers:
# Print numbers 1 through 4
for value in range(1, 5):
print(value)
Output:
1
2
3
4
Note that range()
stops one number before the end value you specify.
Using range() to Make a List of Numbers
# Create a list of numbers
numbers = list(range(1, 6))
print(numbers)
Output:
[1, 2, 3, 4, 5]
You can also use range()
to create lists with specific patterns:
# Even numbers from 2 to 10
even_numbers = list(range(2, 11, 2))
print(even_numbers)
Output:
[2, 4, 6, 8, 10]
Creating Lists with Loops
# Create a list of squares
squares = []
for value in range(1, 11):
squares.append(value**2)
print(squares)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Simple Statistics with Lists
Python provides several functions for mathematical statistics:
# Statistical functions
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits)) # 0
print(max(digits)) # 9
print(sum(digits)) # 45
List Comprehensions
List comprehensions allow you to generate lists in just one line of code:
# Create squares using list comprehension
squares = [value**2 for value in range(1, 11)]
print(squares)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The syntax is: list_name = [expression for value in range()]
Working with Part of a List
Slicing a List
You can work with a specific group of items in a list using a slice:
# Slice a list
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) # First three elements
Output:
['charles', 'martina', 'michael']
Slice Variations
players = ['charles', 'martina', 'michael', 'florence', 'eli']
# From beginning to index 4
print(players[:4])
# From index 2 to end
print(players[2:])
# Last three elements
print(players[-3:])
# Every second element
print(players[::2])
Output:
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
['charles', 'michael', 'eli']
Looping Through a Slice
# Loop through part of a list
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
Output:
Here are the first three players on my team:
Charles
Martina
Michael
Copying a List
To copy a list, you can make a slice that includes the entire original list:
# Copy a list
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] # Creates a copy
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
If you simply assign one list to another (friend_foods = my_foods
), you're not making a copy. Both variables point to the same list!
Tuples
Lists work well for storing collections of items that can change throughout the life of a program. However, sometimes you'll want to create a list of items that cannot change. Python calls these immutable lists tuples.
Defining a Tuple
# Define a tuple
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
Output:
200
50
Tuples are Immutable
# This will cause an error
dimensions = (200, 50)
dimensions[0] = 250 # TypeError: 'tuple' object does not support item assignment
Looping Through a Tuple
# Loop through a tuple
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
Output:
200
50
Writing Over a Tuple
Although you can't modify a tuple, you can assign a new value to a variable that represents a tuple:
# Reassign a tuple
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
Output:
Original dimensions:
200
50
Modified dimensions:
400
100
Code Formatting Guidelines (PEP 8)
Python Enhancement Proposal 8 (PEP 8) provides guidelines for formatting Python code:
Indentation
- Use 4 spaces per indentation level
- Don't mix tabs and spaces
Line Length
- Limit lines to 79 characters maximum
- For docstrings or comments, limit to 72 characters
Blank Lines
- Use blank lines to group parts of your program visually
- Don't overuse blank lines within functions or classes
Summary
In this chapter, you learned how to:
- Loop through lists efficiently using
for
loops - Avoid common indentation and syntax errors
- Generate numerical lists using
range()
and list comprehensions - Work with portions of lists using slices
- Copy lists properly
- Use tuples for data that shouldn't change
- Follow Python coding style guidelines
These techniques form the foundation for working with collections of data in Python, and you'll use them frequently in larger programs.