Python List Comprehension

List comprehension is a concise and expressive way of creating lists in Python. It allows you to define a list and its elements within a single line of code, combining the functionality of a for loop, optional if conditions, and even nested loops. List comprehensions are preferred for their readability and efficiency compared to traditional for loops.

  1. Simple For Loop List Comprehension:

This type of list comprehension is used to create a list by iterating over elements from an iterable (e.g., list, tuple, string) without any filtering or conditions. Here’s an example:

# Example list
numbers = [1, 2, 3, 4, 5]

# List comprehension without filtering or conditions
new_list = [num for num in numbers]

print(new_list) # Output: [1, 2, 3, 4, 5]
  1. Loop and If Condition List Comprehension:

This type of list comprehension includes an if condition to filter elements while iterating over the iterable. Only elements that satisfy the condition are included in the new list. Here’s an example:

# Example list
numbers = [1, 2, 3, 4, 5, 6]

# List comprehension with an if condition
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers) # Output: [2, 4, 6]
  1. Loop and If-Else Condition List Comprehension:
# Example list
numbers = [1, 2, 3, 4, 5, 6]

# List comprehension with if-else condition
result = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]

print(result)
# Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

This type of list comprehension allows you to perform different operations based on the if-else condition while iterating over the iterable. Here’s an example:

  1. Nested Loop List Comprehension:

This type of list comprehension allows you to use nested loops for creating more complex lists by iterating over multiple iterables simultaneously. Here’s an example:

# Example nested loops
colors = ['red', 'green', 'blue']
objects = ['ball', 'box', 'pen']

# List comprehension with nested loops
combinations = [f"{color} {obj}" for color in colors for obj in objects]

print(combinations)
# Output: ['red ball', 'red box', 'red pen', 'green ball', 'green box', 'green pen', 'blue ball', 'blue box', 'blue pen']

Shallow Copy and Deep Copy of Lists in Python:

In Python, when dealing with lists or other compound data structures, understanding the concepts of shallow copy and deep copy is crucial. Both concepts involve creating a new copy of an existing list, but they differ in how they handle nested objects within the list.

  1. Shallow Copy:

A shallow copy of a list creates a new list object but does not create copies of the elements inside the list. Instead, it copies references to the original objects. This means that changes made to nested objects within the copied list will affect the original list, and vice versa. To perform a shallow copy, you can use the `copy()` method or the slicing notation `[:]`. Example of Shallow Copy:

import copy

# Original list with a nested list
original_list = [[1, 2, 3], [4, 5, 6]]

# Shallow copy using the copy() method
shallow_copy1 = original_list.copy()

# Shallow copy using slicing notation
shallow_copy2 = original_list[:]

# Modifying a nested element in the copied list
shallow_copy1[0][0] = 99

print("Original List:", original_list)
# Output: Original List: [[99, 2, 3], [4, 5, 6]]

print("Shallow Copy 1:", shallow_copy1)
# Output: Shallow Copy 1: [[99, 2, 3], [4, 5, 6]]

print("Shallow Copy 2:", shallow_copy2)
# Output: Shallow Copy 2: [[99, 2, 3], [4, 5, 6]]
  1. Deep Copy:

A deep copy of a list creates a new list object and also recursively creates copies of all the nested objects within the original list. In other words, the copied list and its nested objects are entirely independent of the original list and its nested objects. To perform a deep copy, you need to use the `deepcopy()` function from the `copy` module. Example of Deep Copy:

import copy

# Original list with nested lists
original_list = [[1, 2, 3], [4, 5, 6]]

# Creating a deep copy
deep_copy = copy.deepcopy(original_list)

# Modifying a nested element in the deep copy
deep_copy[0][0] = 99

print("Original List:", original_list)
# Output: Original List: [[1, 2, 3], [4, 5, 6]]

print("Deep Copy:", deep_copy)
# Output: Deep Copy: [[99, 2, 3], [4, 5, 6]]

Shallow copy is faster and suitable when you want to create a new list but share references to nested objects. Deep copy is appropriate when you need an entirely independent copy of the original list and all its nested objects.

Python List Methods And Functions

Lists in Python have many built-in methods that you can use to modify or manipulate the list. Here are some of the most commonly used methods:

  1. append() – It is used to add an element to the end of the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Add an element to the end of the list
my_list.append('date')

# Print the updated list
print(my_list)
  1. extend() – It is used to add the elements of another list to the end of the list or to combine two lists.
# Define a list
my_list = ['apple', 'banana']

# Extend the list with a tuple
my_list.extend(('cherry', 'date'))

# Extend the list with a set

my_list.extend({'elderberry', 'fig'})

# Print the updated list
print(my_list)
  1. insert() – It is used to insert an element at a specific position in the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Insert an element at index 1
my_list.insert(1, 'date')

# Print the updated list
print(my_list)

         4. remove() – It is used to remove the first occurrence of an element from the list.

# Define a list
my_list = ['apple', 'banana', 'cherry', 'banana']

# Remove the first occurrence of 'banana'
my_list.remove('banana')

# Print the updated list
print(my_list)
  1. pop() – It removes and returns the element at a specific position in the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Remove and return the last element
removed_element = my_list.pop()

# Print the updated list and the removed element
print("Updated list:", my_list)
print("Removed element:", removed_element)

 6. sort() – It sorts the elements of the list in ascending order.

# Define a list of numbers
my_list = [3, 1, 4, 1, 5, 9, 2, 6]

# Sort the list in descending order
my_list.sort(reverse=True)

# Print the sorted list
print(my_list)

    7 .reverse() – It reverses the order of the elements in the list.

# Define a list of strings
my_list = ['apple', 'banana', 'cherry']

# Reverse the list
my_list.reverse()

# Print the reversed list
print(my_list)
  1. clear() – It is used to remove all elements from a list, effectively emptying the list. After the clear() function is applied to a list, the list becomes empty with a length of 0.
# Define a list of strings
my_list = ['apple', 'banana', 'cherry']

# Clear all elements from the list
my_list.clear()

# Print the cleared list
print(my_list)
  1. copy() – It creates a shallow copy of a list. The shallow copy means that a new list is created with the same elements as the original list, but the elements themselves are not duplicated. Any changes made to the elements in the copied list will also affect the original list, and vice versa.
# Define a list with immutable elements
my_list = [1, 2, 3]

# Create a shallow copy of the list
my_list_copy = my_list.copy()

# Modify the copied list
my_list_copy.append(4)

# Print both lists
print("Original list:", my_list)
print("Copied list:", my_list_copy)
  1. index() – It is used to find the index of the first occurrence of a specified element within a list. If the element is not found in the list, it raises a ValueError.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Find the index of 'banana'
index_of_banana = my_list.index('banana')

# Print the index
print("Index of 'banana':", index_of_banana)
  1. count() – It is used to count the number of occurrences of a specified element in a list.
# Define a list
my_list = ['apple', 'banana', 'cherry', 'banana', 'apple']

# Count occurrences of 'banana'
banana_count = my_list.count('banana')

# Print the count
print("Count of 'banana':", banana_count)

Updating list values:

Lists in Python are mutable, and their values can be updated by using the slice and assignment the ( = ) operator.

# Define a list
my_list = [1, 2, 3, 4, 5]

# Remove elements at indices 1 to 3
my_list[1:4] = []

# Print the updated list
print(my_list)

Built-in function for Python lists:

Here are some examples of commonly used built-in functions for lists in Python:

  1. len(): It returns the length of the list.
# Define a list
my_list = [1, 2, 3, 4, 5]

# Get the length of the list
list_length = len(my_list)

# Print the length
print("Length of the list:", list_length)
  1. max(): It returns the largest element in the list.
# Define a list of numbers
my_list = [1, 5, 3, 9, 2]

# Get the largest element in the list
largest_element = max(my_list)

# Print the largest element

print("Largest element:", largest_element)
  1. min(): It returns the smallest element in the list.
# Define a list of numbers
my_list = [10, 5, 20, 3, 8]

# Get the smallest element in the list
smallest_element = min(my_list)

# Print the smallest element
print("Smallest element:", smallest_element)
  1. sum(): It returns the sum of all elements in the list.
# Define a list of numbers
my_list = [1, 2, 3, 4, 5]

# Calculate the sum of the elements in the list
total_sum = sum(my_list)

# Print the total sum
print("Sum of the list:", total_sum)

       5. sorted(): It returns a new sorted list.

# Define a list of numbers
my_list = [5, 2, 9, 1, 5, 6]

# Get a new sorted list
sorted_list = sorted(my_list)

# Print the sorted list
print("Sorted list:", sorted_list)
  1. list(): It converts an iterable to a list.
# Define a tuple
my_tuple = (1, 2, 3, 4)

# Convert the tuple to a list
my_list = list(my_tuple)

# Print the list
print("List from tuple:", my_list)

       7. any(): It returns True if at least one element in the list is True.

# Define a list of Boolean values
my_list = [False, False, True, False]

# Check if any element is True
result = any(my_list)

# Print the result
print("Any True in the list:", result)
  1. all(): It returns True if all elements in the list are True.
# Define a list of Boolean values
my_list = [True, True, True]

# Check if all elements are True
result = all(my_list)

# Print the result
print("All True in the list:", result)

        9. enumerate(): It returns an iterator that contains tuples of (index, element) pairs.

# Define a list
my_list = ['apple', 'banana', 'cherry']

# Use enumerate to get index and element
for index, element in enumerate(my_list):
print(f"Index: {index}, Element: {element}")

# Output:

Index: 0, Element: apple
Index: 1, Element: banana
Index: 2, Element: cherry
  1. zip(): It returns an iterator that aggregates elements from multiple lists into tuples.
# Define two lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# Use zip to combine them into tuples
zipped = zip(list1, list2)

# Convert the zipped object to a list and print
zipped_list = list(zipped)
print(zipped_list)

        11.reversed(): It returns a reverse iterator that can be used to iterate over a list in reverse order.

# Define a list
my_list = [1, 2, 3, 4, 5]

# Convert the reversed iterator to a list
reversed_list = list(reversed(my_list))

# Print the reversed list
print(reversed_list)

Python Lists

Python Tutorial › Data Structures › Lists

Python Lists

BeginnerLesson 18 of 4712 min read11 runnable examples

A list stores many values in one variable, in order. You will use lists in almost every Python program you write, from a shopping cart to a set of test results.

In this lesson
  • Create lists of any type
  • Read items with indexing and slicing
  • Add, change and remove items
  • Loop through a list
  • Sort a list two ways
  • Avoid the shared-list copy bug

What is a list in Python?

A list is written with square brackets, with items separated by commas. One list can hold numbers, strings, booleans, None and even other lists.

Python
fruits = ["apple", "banana", "cherry"]mixed = [1, "two", 3.0, True, None]empty = [] print(fruits)print(type(fruits))print(len(mixed), len(empty))
Output
['apple', 'banana', 'cherry']
<class 'list'>
5 0
Note

Lists are ordered (items keep their position), mutable (you can change them after creating them) and they allow duplicates.

You can also build a list from any iterable with list(), for example from a string or a range.

Python
print(list("abc"))print(list(range(1, 6)))
Output
['a', 'b', 'c']
[1, 2, 3, 4, 5]

Indexing and slicing

Every item has a position, called its index. Counting starts at 0 from the left and at -1 from the right.

Python
nums = [10, 20, 30, 40, 50] print(nums[0])      # first itemprint(nums[-1])     # last itemprint(nums[1:4])    # items at index 1, 2, 3print(nums[::-1])   # reversed copy
Output
10
50
[20, 30, 40]
[50, 40, 30, 20, 10]
Tip

A slice nums[start:stop] includes start but stops before stop. That is why nums[1:4] returns three items. Leave out start or stop to go from the beginning or to the end.

Reading an index that does not exist raises an IndexError. A slice never does: it just returns fewer items.

Python
nums = [10, 20, 30]print(nums[1:10])print(nums[5])
Output
[20, 30]
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(nums[5])
          ~~~~^^^
IndexError: list index out of range

Add, change and remove items

Python
cart = ["pen", "book"] cart.append("bag")        # add to the endcart.insert(1, "ink")     # add at index 1cart[0] = "pencil"        # replace an itemprint(cart) last = cart.pop()         # remove and return the last itemprint(last, cart) cart.remove("ink")        # remove by valueprint(cart)
Output
['pencil', 'ink', 'book', 'bag']
bag ['pencil', 'ink', 'book']
['pencil', 'book']

Python list methods you will use most

MethodWhat it doesReturns
append(x)Adds x to the endNone
insert(i, x)Adds x before index iNone
extend(items)Adds every item from another iterableNone
remove(x)Removes the first x; raises ValueError if it is missingNone
pop(i=-1)Removes the item at index ithe removed item
index(x)Finds the position of the first xint
count(x)Counts how often x appearsint
sort() / reverse()Reorders the list in placeNone
clear()Removes every itemNone
copy()Makes a shallow copya new list

append() adds its argument as one item, while extend() adds each item separately:

Python
a = [1, 2]a.append([3, 4])print(a) b = [1, 2]b.extend([3, 4])print(b)
Output
[1, 2, [3, 4]]
[1, 2, 3, 4]

Loop through a list

A for loop visits each item in order. enumerate() gives you the position and the item together, so you do not need a counter variable.

Python
tasks = ["write tests", "run tests", "fix bugs"] for number, task in enumerate(tasks, start=1):    print(f"{number}. {task}")
Output
1. write tests
2. run tests
3. fix bugs

Use in to check whether a value is in a list:

Python
browsers = ["chromium", "firefox", "webkit"]print("firefox" in browsers)print("edge" in browsers)
Output
True
False

Sort a list

Python
scores = [72, 95, 58, 88] print(sorted(scores))          # new sorted listprint(scores)                  # original is unchanged scores.sort(reverse=True)      # sorts in placeprint(scores)
Output
[58, 72, 88, 95]
[72, 95, 58, 88]
[95, 88, 72, 58]
Watch out

scores.sort() changes the list and returns None. Writing scores = scores.sort() throws your list away. Use sorted(scores) when you need a new list.

Pass key= to sort by something other than the value itself, such as the length of each word:

Python
words = ["banana", "fig", "apple"]print(sorted(words, key=len))
Output
['fig', 'apple', 'banana']

Copy a list without surprises

Assigning a list to a new name does not copy it. Both names point at the same list, so a change through one name shows up in the other.

Python
a = [1, 2]b = a            # b is the SAME list, not a copyb.append(3)print(a) c = a.copy()     # c is a new listc.append(4)print(a, c)
Output
[1, 2, 3]
[1, 2, 3] [1, 2, 3, 4]

Check your understanding

Predict the output

x = [1, 2, 3]y = x * 2print(y, len(y))

Quick quiz

1. What does [10, 20, 30][-1] return?

2. Which call removes and returns the last item?

3. After b = a and b.append(3), what is in a?

4. What does [3, 1, 2].sort() evaluate to?

Exercise: remove duplicate emails

You have a list of signup emails with repeats. Build a list that keeps each email once, in the order it first appeared.

Input
["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
Expected output
['a@x.com', 'b@x.com', 'c@x.com']
Hint 1

A set removes duplicates but does not keep the order.

Hint 2

Dictionary keys are unique and keep insertion order.

Program Practice: Python list programs

Practise what you just learned. Start with the easy programs and work up.

Python lists FAQ

What is the difference between a list and a tuple in Python?

A list is mutable, so you can add, change and remove items. A tuple is immutable: once created, its items cannot change. Use a tuple for fixed data such as coordinates. See List vs Tuple.

How do I check if an item is in a list?

Use the in operator: "apple" in fruits returns True or False.

What is the difference between append() and extend()?

append(x) adds x as one item, even if x is a list. extend(items) adds each item of items separately.

How do I remove duplicates from a list and keep the order?

Use list(dict.fromkeys(items)). list(set(items)) also removes duplicates but does not keep the original order.

Can a Python list hold different data types?

Yes. A list can mix integers, strings, floats, booleans, None and other lists, although lists of one type are easier to work with.