Skip to content

Python 3 - Lists

Sequences are fundamental ordered collections in Python. Each item in a sequence has an assigned index, starting from 0 for the first item.

Python provides several built-in sequence types, with lists and tuples being the most common. This section focuses on lists.

Common operations applicable to sequences include indexing, slicing, addition (concatenation), multiplication (repetition), and membership testing (in, not in). Python also has built-in functions like len(), max(), and min() that work with sequences.

Lists are arguably the most versatile sequence type in Python. They are defined by enclosing comma-separated values (items) within square brackets []. A key feature of lists is that they are mutable, meaning their contents can be changed after creation. Furthermore, items within a list do not need to be of the same data type.

Creating lists:

# A list of strings
subjects = ['Physics', 'Chemistry', 'Math']
# A list of integers
years = [1997, 2000, 2023]
# A list with mixed data types
mixed_list = ['Alice', 30, 1.68, True]
# An empty list
empty_list = []
# Creating a list using the list() constructor from another iterable
name_chars = list('Python') # Results in ['P', 'y', 't', 'h', 'o', 'n']

Like strings, list indices start at 0. Lists support slicing, concatenation, and other sequence operations.

Use square brackets [] with the index or a slice to access list elements:

#!/usr/bin/env python3
subjects = ['Physics', 'Chemistry', 'Math', 'Biology']
numbers = [1, 2, 3, 4, 5, 6, 7]
# Accessing single elements
print(f"subjects[0]: {subjects[0]}") # Output: Physics
print(f"subjects[-1]: {subjects[-1]}") # Output: Biology
# Slicing lists
print(f"numbers[1:5]: {numbers[1:5]}") # Output: [2, 3, 4, 5]
print(f"subjects[:2]: {subjects[:2]}") # Output: ['Physics', 'Chemistry']
print(f"numbers[::2]: {numbers[::2]}") # Output: [1, 3, 5, 7]

Executing the code produces:

subjects[0]: Physics
subjects[-1]: Biology
numbers[1:5]: [2, 3, 4, 5]
subjects[:2]: ['Physics', 'Chemistry']
numbers[::2]: [1, 3, 5, 7]

Because lists are mutable, you can change their content. You can update single elements or slices by assigning new values.

#!/usr/bin/env python3
data = ['physics', 'chemistry', 1997, 2000]
print(f"Original list: {data}")
# Update a single element
data[2] = 2001
print(f"After updating index 2: {data}")
# Update a slice
data[0:2] = ['Biology', 'Math']
print(f"After updating slice [0:2]: {data}")

You can also add elements using methods like append(), insert(), and extend() (discussed later).

Executing the code produces:

Original list: ['physics', 'chemistry', 1997, 2000]
After updating index 2: ['physics', 'chemistry', 2001, 2000]
After updating slice [0:2]: ['Biology', 'Math', 2001, 2000]

You can remove elements from a list in several ways:

  • del statement: Removes an element or slice by index.
  • remove() method: Removes the first occurrence of a specific value.
  • pop() method: Removes and returns the element at a specific index (defaults to the last element).
#!/usr/bin/env python3
items = ['apple', 'banana', 'cherry', 'banana', 'date']
print(f"Original list: {items}")
# Using 'del' by index
del items[2] # Removes 'cherry'
print(f"After del items[2]: {items}")
# Using 'remove()' by value
items.remove('banana') # Removes the first 'banana'
print(f"After items.remove('banana'): {items}")
# Using 'pop()' (last element by default)
last_item = items.pop()
print(f"Popped item: {last_item}, List after pop(): {items}")
# Using 'pop()' with an index
first_item = items.pop(0)
print(f"Popped item: {first_item}, List after pop(0): {items}")

Executing the code produces:

Original list: ['apple', 'banana', 'cherry', 'banana', 'date']
After del items[2]: ['apple', 'banana', 'banana', 'date']
After items.remove('banana'): ['apple', 'banana', 'date']
Popped item: date, List after pop(): ['apple', 'banana']
Popped item: apple, List after pop(0): ['banana']

Lists support standard sequence operations:

OperationResultDescription
len([1, 2, 3])3Length
[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation
['Hi!'] * 3['Hi!', 'Hi!', 'Hi!']Repetition
3 in [1, 2, 3]TrueMembership
for x in [1, 2, 3]: print(x, end=' ')1 2 3Iteration

Indexing and slicing work just like with strings. Lists can also contain other lists, creating nested structures often used to represent matrices or tables.

#!/usr/bin/env python3
languages = ['C++', 'Java', 'Python', 'Go']
print(f"languages[2]: {languages[2]}") # Output: Python
print(f"languages[-1]: {languages[-1]}") # Output: Go
print(f"languages[1:]: {languages[1:]}") # Output: ['Java', 'Python', 'Go']
# Nested list (Matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(f"matrix[1]: {matrix[1]}") # Output: [4, 5, 6] (second row)
print(f"matrix[1][1]: {matrix[1][1]}") # Output: 5 (element at row 1, col 1)

Python includes several built-in functions that are useful with lists:

FunctionDescription
len(list)Returns the number of items in the list.
max(list)Returns the item with the maximum value in the list.
min(list)Returns the item with the minimum value in the list.
sum(list)Returns the sum of all numeric items in the list.
sorted(list, reverse=False)Returns a new sorted list from the items in the original list. Does not modify the original.
list(iterable)Converts an iterable (like a tuple, string, or range) into a list.

Lists have several built-in methods that modify the list in-place (unless noted otherwise).

Method SignatureDescription
list.append(item)Adds item to the end of the list.
list.extend(iterable)Appends all items from iterable to the end of the list.
list.insert(index, item)Inserts item at the specified index.
list.remove(value)Removes the first occurrence of value from the list. Raises ValueError if not found.
list.pop([index])Removes and returns the item at index (defaults to the last item). Raises IndexError if the list is empty or the index is out of range.
list.clear()Removes all items from the list.
list.index(value[, start[, end]])Returns the index of the first occurrence of value. Raises ValueError if not found. Optional start and end limit the search.
list.count(value)Returns the number of times value appears in the list.
list.sort(key=None, reverse=False)Sorts the items of the list in-place. key specifies a function to customize sort order, reverse=True sorts descending.
list.reverse()Reverses the elements of the list in-place.
list.copy()Returns a shallow copy of the list.

Example usage:

#!/usr/bin/env python3
numbers = [3, 1, 4, 1, 5, 9]
print(f"Initial list: {numbers}")
numbers.append(2)
print(f"After append(2): {numbers}")
numbers.insert(0, 6) # Insert 6 at the beginning
print(f"After insert(0, 6): {numbers}")
numbers.sort()
print(f"After sort(): {numbers}")
numbers.reverse()
print(f"After reverse(): {numbers}")
print(f"Count of 1: {numbers.count(1)}")
print(f"Index of 4: {numbers.index(4)}")
popped_item = numbers.pop(1)
print(f"Popped item at index 1: {popped_item}, List now: {numbers}")