Python List Operations
Table of Contents
In the last lesson, we learned about Python Introduction to Lists. Now let’s read, change, combine, and check list items.
Let’s Do Things with Lists
We know how to create a list. We know how to access items. We know how to add and remove items.
But there is more we can do with lists. We can combine them. Repeat them. Check if something is inside. Find the smallest or largest number. Add up all the numbers. And more.
These are called list operations. They are the everyday tools we use when working with lists.
Let’s go through them one by one.
Joining Lists with + in Python
We can join two lists using the + operator. This is called concatenation.
list1 = [1, 2, 3]list2 = [4, 5, 6]combined = list1 + list2print(combined)Output
[1, 2, 3, 4, 5, 6]It creates a new list with all the items from both lists. The original lists are not changed.
We can also use += to add items to an existing list.
list1 = [1, 2, 3]list1 += [4, 5]print(list1)Output
[1, 2, 3, 4, 5]That modifies list1 in place.
Repeating a List with * in Python
We can repeat a list using the * operator.
numbers = [1, 2]repeated = numbers * 3print(repeated)Output
[1, 2, 1, 2, 1, 2]It repeats the list the given number of times. Again, it creates a new list.
This is useful when we want to initialize a list with the same value multiple times.
zeros = [0] * 5print(zeros)Output
[0, 0, 0, 0, 0]But let’s be careful when the list contains mutable objects like other lists. Because the repetition copies the reference, not the object.
Checking Membership with in
We can check if an item is in a list using in.
fruits = ["apple", "banana", "orange"]print("banana" in fruits)Output
Trueprint("grape" in fruits)Output
FalseWe can also use not in to check the opposite.
print("grape" not in fruits)Output
TrueThis is very handy. It is one of the most common operations on lists.
Looping Through a List in Python
We already saw this in the introduction. But it is worth repeating because it is so common.
fruits = ["apple", "banana", "orange"]for fruit in fruits: print(fruit)Output
applebananaorangeWe can also loop with index using enumerate().
for index, fruit in enumerate(fruits): print(f"{index}: {fruit}")Output
0: apple1: banana2: orangeThat gives us both the position and the value.
Finding the Length with len()
len() gives us the number of items in a list.
fruits = ["apple", "banana", "orange"]print(len(fruits))Output
3It works on any sequence. Lists, strings, tuples, dictionaries. Very useful.
Finding the Smallest and Largest in a Python List
Python has built-in functions min() and max() for lists of numbers (or any comparable items).
numbers = [5, 2, 9, 1, 7]print(min(numbers))print(max(numbers))Output
19They also work on strings. It compares them alphabetically.
words = ["banana", "apple", "cherry"]print(min(words))print(max(words))Output
applecherryAdding Up Numbers with sum()
sum() adds up all the numbers in a list.
numbers = [1, 2, 3, 4, 5]print(sum(numbers))Output
15It only works on numbers. If we try it on strings, we get an error.
words = ["a", "b"]print(sum(words)) # Error!Sorting with sorted()
sorted() returns a new list with the items sorted. The original list is not changed.
numbers = [5, 2, 9, 1, 7]sorted_numbers = sorted(numbers)print(sorted_numbers)Output
[1, 2, 5, 7, 9]We can sort in reverse order.
print(sorted(numbers, reverse=True))Output
[9, 7, 5, 2, 1]If we want to sort the list in place, we use the .sort() method. sorted() is a built-in function that works on any iterable.
Checking any() and all() in Python
any() returns True if at least one item is truthy.
numbers = [0, 0, 1, 0]print(any(numbers))Output
TrueBecause there is a 1 (which is truthy).
all() returns True only if all items are truthy.
numbers = [1, 2, 3]print(all(numbers))Output
Truenumbers = [1, 0, 3]print(all(numbers))Output
FalseBecause 0 is falsy.
These are useful for quick checks.
Python List Operations: A Real-Life Example
Let’s combine lists of names and check some things.
group1 = ["Alex", "Sam", "John"]group2 = ["Emma", "David", "Sam"]
all_names = group1 + group2print(f"All names: {all_names}")print(f"Total names: {len(all_names)}")
if "Sam" in all_names: print("Sam is in the list")
unique_names = list(set(all_names))print(f"Unique names: {unique_names}")Output
All names: ['Alex', 'Sam', 'John', 'Emma', 'David', 'Sam']Total names: 6Sam is in the listUnique names: ['Alex', 'Sam', 'John', 'Emma', 'David']That shows concatenation, length, membership, and even a quick way to remove duplicates using a set.
Common Mistakes with Python List Operations
Mistake 1: Using + with a List and a Non-List
numbers = [1, 2, 3]numbers + 4 # Error!We can only concatenate a list with another list.
So what do we do? We wrap it in a list.
numbers + [4]Mistake 2: Thinking sorted() Changes the Original
numbers = [3, 1, 2]sorted(numbers)print(numbers)Output
[3, 1, 2]Because sorted() returns a new list. So what do we do? We assign it.
numbers = sorted(numbers)Or we use the .sort() method.
Mistake 3: Using sum() on Non-Numbers
words = ["hello", "world"]sum(words) # Error!sum() only works on numbers.
Mistake 4: Using min() or max() on Mixed Types
mixed = [1, "hello", 3]min(mixed) # Error!We cannot compare numbers and strings. So min and max fail.
Mistake 5: Forgetting That in Is Case-Sensitive for Strings
names = ["Alex", "Sam"]print("alex" in names)Output
FalseBecause “alex” is not the same as “Alex”. So let’s use a loop with .lower() if we need case-insensitive checks.
Next, we will learn about Python List Methods and use built-in tools to modify lists.