List

Learn about lists in Python.

Ali Berro

By Ali Berro

16 min read Section
From: Python Fundamentals: From Zero to Hero

List

A list is an array-like structure used to store multiple objects of same/different data types.

Creating a List

A list can be created by enclosing items in square brackets [], separated by commas:

empty_list = []
numbers = [1, 2, 3, 4]
mixed = [1, 1.2, True, None, "hello"]
repetition = ["ABC", "ABC", "ABC"]
nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

A list can also be created using the list() constructor which takes an iterable and converts it into a list.

chars = list("hello") # ['h', 'e', 'l', 'l', 'o']
numbers = list(range(5)) # [0, 1, 2, 3, 4]

Common Sequence Operations

Lists are sequences, which means they support common sequence operations that work with other sequence types like strings and tuples. These operations include:

  • Membership: Check if an element exists
  • Length: Get the number of elements
  • Minimum and Maximum: Find the smallest and largest elements
  • Counting: Count the number of occurrences of an element
  • Searching: Find the index of an element
  • Indexing: Access elements by their position
  • Slicing: Extract portions of the list
  • Concatenation: Combine lists
  • Repetition: Repeat lists

Accessing Elements at Specific Index

Individual elements in a list can be accessed using their index. In Python, indices start at 0, so the first element is at index 0, the second at index 1, and so on.

fruits = ["A", "B", "C", "D"]
print(fruits[0]) # A
print(fruits[1]) # B
print(fruits[2]) # C
print(fruits[3]) # D

Negative indices count from the end of the list. -1 refers to the last element, -2 to the second-to-last, and so on.

fruits = ["A", "B", "C", "D"]
print(fruits[-1]) # D
print(fruits[-2]) # C
print(fruits[-3]) # B
print(fruits[-4]) # A

Warning

Accessing an index that doesn’t exist will raise an IndexError:

fruits = ["apple", "banana"]
print(fruits[5]) # IndexError: list index out of range

Mutability

Lists are mutable, which means their contents can be changed after they are created. This is one of the key differences between lists and tuples.

Changing Elements at Specific Index

The value of an element can be changed at a specific index by assigning a new value to it:

numbers = [1, 2, 3, 4, 5]
print(numbers) # [1, 2, 3, 4, 5]
numbers[0] = 10
print(numbers) # [10, 2, 3, 4, 5]

Slicing

Slicing allows a portion of a list to be extracted. The syntax is list[start:stop:step] where start is the index of the first item to include (inclusive), stop is the index of the first item to exclude (exclusive), and step is the number of items to skip between each item which defaults to 1.

x = ["A", "B", "C", "D"]
print(x[0:2]) #["A", "B"]
print(x[1:2]) #["B"]
print(x[1:4]) #["B", "C", "D"]
print(x[0:4:2]) #["A", "C"]
print(x[-1:0:-2]) #["D", "B"]
print(x[-1:0:1]) #[]
print(x[-4:4]) #["A", "B", "C", "D"]

The start, end and step indices can be omitted. If start is omitted, it defaults to 0. If end is omitted, it defaults to the length of the list. If step is omitted, it defaults to 1.

x = ["A", "B", "C", "D"]
print(x[:2]) #["A", "B"]
print(x[1:]) #["B", "C", "D"]
print(x[:]) #["A", "B", "C", "D"]
print(x[-1::]) #["D"]
print(x[:-1:]) #["A", "B", "C"]

Tip

Slicing creates a new list, so modifying a slice doesn’t affect the original list unless you assign it back.

Range Update

Instead of changing individual items, a range of items can be changed by assigning it to a new iterable.

x = ["A", "B", "C", "D"]
x[0] = "E"
print(x) #["E", "B", "C", "D"]
x[-1] = "F"
print(x) #["E", "B", "C", "F"]
x[::2] = ["G", "H"]
print(x) #["G", "B", "H", "F"]
x[1:2] = ["X", "Y", "Z"]
print(x) #["G", "X", "Y", "Z", "H", "F"]
x[::2] = "Hey"
print(x) #["H", "X", "e", "Z", "y", "F"]

Adding elements to a list

To add elements to a list, the methods append(), extend(), and insert() can be used.

  • append() adds a single element to the end of the list
  • extend() adds all elements from an iterable to the end of the list
  • insert() adds an element at a specific index
x = ["A", "B", "C", "D"]
x.append("E")
print(x) #["A", "B", "C", "D", "E"]
x.extend(["F", "G"])
print(x) #["A", "B", "C", "D", "E", "F", "G"]
x.insert(1, 0)
print(x) #["A", 0, "B", "C", "D", "E", "F", "G"]

Removing elements from a list

To remove elements from a list, the methods pop(), remove(), and clear() can be used.

  • pop() removes and returns the element at a specific index. If no index is specified, it removes and returns the last element. If there is no element at the specified index or the list is empty, it raises an IndexError.
  • remove() removes the first occurrence of a specified value. If the value doesn’t exist in the list, it raises a ValueError.
  • clear() removes all elements from the list, making it empty.
x = ["A", "B", "C", "B", "D"]
x.remove("B")
print(x) #["A", "C", "B", "D"]
x.pop()
print(x) #["A", "C", "B"]
x.pop(0)
print(x) #["C", "B"]
x.clear()
print(x) #[]

Looping through a list

A list can be iterated using a for loop or a while loop.

for loop

The most common and Pythonic way to loop through a list is using a for loop:

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

If the indices are needed, then a for loop could be used in conjunction with range():

fruits = ["apple", "banana", "orange"]
for i in range(len(fruits)):
print(i, ":", fruits[i])

while loop

Another way to iterate through a list is using a while loop:

fruits = ["apple", "banana", "orange"]
i = 0
while i < len(fruits):
print(fruits[i])
i += 1

Tip

for loops are generally preferred for iterating through lists as they are more readable and less error-prone. while loops are generally used when the number of iterations is unknown or when the loop needs to be terminated by a condition other than the number of iterations.

in and not in operators

To check if an element exists in a list, the in and not in operators can be used:

fruits = ["apple", "banana", "orange"]
if "apple" in fruits:
print("Apple is in the list")
if "grape" not in fruits:
print("Grape is not in the list")
print("banana" in fruits) # True
print("mango" not in fruits) # True

Note

Notice how the not in operator is written, it is not two operators in and not, but a single operator not in.

The assignment operator (Revisited)

When we usually write x = y, we are binding the value of y to the variable x. Since every value in Python is basically an object, then knowing the mutability of y (if y is mutable or immutable) is important. If y is a mutable object, then both x and y will be able to change it (which may not be desirable). Consider the following example:

assignment-immutable-example.py
x = 3
y = x
x += 1
y -= 1
print(x) #4
print(y) #2

Since x and y are both integers, which are immutable, then x and y will change independently. Another example:

assignment-mutable-example.py
x = [1, 2, 3]
y = x
x.append(4)
print(x) # [1, 2, 3, 4]
print(y) # [1, 2, 3, 4]

Here we were intending on copying the list so that each variable would have its own copy of the list. Since x and y are both lists, which are mutable, then x and y will change together. This is not what we intended, so we need to use a different approach.

assignment-mutable-example2.py
x = [1, 2, 3]
y = x.copy()
x.append(4)
print(x) # [1, 2, 3, 4]
print(y) # [1, 2, 3]

The Identity Operator (is) and (is not)

The identity operator is and is not are used to check if two variables refer to the same object in memory.

x = [1, 2, 3]
y = [1, 2, 3]
print(x == y) # True
print(x is y) # False
x = [1, 2, 3]
y = x
print(x == y) # True
print(x is y) # True
print(x is not y) # False

Note

The identity operator is is different from the equality operator ==. The equality operator == checks if two objects have the same value, while the identity operator is checks if two variables refer to the same object in memory.

Tip

For lists, use == to compare values and is to check if two variables point to the same list object. For immutable types like integers and strings, Python may reuse objects, so is might work, but it’s still better to use == for value comparison.

The del keyword

The del keyword is used to delete variables, elements, slices from a list, or to delete the entire list variable:

x = 1
y = [1, 2, 3, 4, 5]
z = [1, 2, 3, 4, 5]
del x
print(x) # NameError: name 'x' is not defined
del y
print(y) # NameError: name 'y' is not defined
del z[0]
print(z) # [2, 3, 4, 5]
del z[1:3]
print(z) # [2, 5]
del z[:]
print(z) # []

Notable List Methods

Notable list methods include:

  • append(e): Inserts an element at the end of the list.
  • pop(i=-1): Removes an element at the given index, default is -1 (last).
  • remove(val): Searches for the first occurrence of the given value and deletes it.
  • clear(): Clears the list.
  • count(e): Returns the number of occurrence of val.
  • index(value): Returns the first index of value.
  • insert(index, val): Inserts an element in the specified index

List as a Sequence

Lists are sequences, so let’s see all the actions in one example:

x = [1,2,3,4,5]
print(x) #[1, 2, 3, 4, 5]
print(len(x)) #5
print(min(x)) #1
print(max(x)) #5
print(sum(x)) #15
print(3 in x) #True
print(10 in x) #False
print(x.count(3)) #1
x.insert(3, 0)
print(x) #[1, 2, 3, 0, 4, 5]
print(x[1::2]) #[2, 0, 5]
print(x * 2) #[1, 2, 3, 0, 4, 5, 1, 2, 3, 0, 4, 5]
print(x + [6, 7]) #[1, 2, 3, 0, 4, 5, 6, 7]

Exercises

Exercise 1: What is the output of the following code

What is the output of the following code:

k = [1, 2, 3, 4, 5, 6]
for i in range(len(k)):
if i in k:
print(i, end=" ")
Answer:

The output is: 1 2 3 4 5

The loop iterates through indices 0, 1, 2, 3, 4, 5 (from range(len(k))). For each index i, it checks if i in k. Since k = [1, 2, 3, 4, 5, 6], the values 1, 2, 3, 4, 5 are in the list, but 0 and 6 are not.

Exercise 2: How to access the number 8 from this list

How to access the number 8 from this list: [[1, 2, 3], [[4, 5, 6], [7, [8, 9]]]]

Answer:

The number 8 can be accessed using nested indexing:

my_list = [[1, 2, 3], [[4, 5, 6], [7, [8, 9]]]]
print(my_list[1][1][1][0]) # Output: 8

Breaking it down:

my_list[1] accesses the second element: [[4, 5, 6], [7, [8, 9]]]

my_list[1][1] accesses the second element of that: [7, [8, 9]]

my_list[1][1][1] accesses the second element of that: [8, 9]

my_list[1][1][1][0] accesses the first element of that: 8

Exercise 3: Printing a list to the console

Write a program that creates a list [1, 2, 3, 4, 5] and prints it to the console.

Print List

Checks: 0 times
Answer:
my_list = [1, 2, 3, 4, 5]
print(my_list)

Exercise 4: Find the sum of the elements in a list

Write a program that reads the size of the list followed by the elements of the list and prints the sum of all elements in the list.

Sum of List Elements

Checks: 0 times
Answer:
size = int(input())
numbers = []
for i in range(size):
numbers.append(int(input()))
total = 0
for num in numbers:
total += num
print(total)

or

size = int(input())
numbers = []
for i in range(size):
numbers.append(int(input()))
print(sum(numbers))

Exercise 5: Reading from the user a list of positive numbers

Write a program that reads the size of the list followed by numbers, then only adds the positive numbers to the list and prints it.

Read Positive Numbers

Checks: 0 times
Answer:
size = int(input())
numbers = []
for i in range(size):
num = int(input())
if num >= 0:
numbers.append(num)
print(numbers)

Exercise 6: Finding the minimum value in a list without the min function

Write a program that reads the size of the list followed by the elements of the list and finds the minimum value without using the min() function.

Find Minimum

Checks: 0 times
Answer:
size = int(input())
numbers = []
for i in range(size):
numbers.append(int(input()))
minimum = numbers[0]
for num in numbers:
if num < minimum:
minimum = num
print(minimum)

Exercise 7: Check if an element is in the list without the in operator

Write a program that reads the size of the list followed by the elements of the list, then reads a target number, and checks if the target number exists in the list without using the in operator. Print "Found" if it exists, otherwise print "Not Found".

Check Membership

Checks: 0 times
Answer:
size = int(input())
numbers = []
for i in range(size):
numbers.append(int(input()))
target = int(input())
found = False
for num in numbers:
if num == target:
found = True
break
if found:
print("Found")
else:
print("Not Found")

Or we could use the else keyword to our advantage:

size = int(input())
numbers = []
for i in range(size):
numbers.append(int(input()))
target = int(input())
for num in numbers:
if num == target:
print("Found")
break
else:
print("Not Found")

Exercise 8: Find all duplicate elements inside a list

Write a program that reads the size of the list followed by the elements of the list and prints all duplicate elements (each duplicate printed only once, in the order they first appear).

Find Duplicates

Checks: 0 times
Answer:
size = int(input())
numbers = []
for i in range(size):
numbers.append(int(input()))
duplicates = []
seen = []
for num in numbers:
if num in seen and num not in duplicates:
duplicates.append(num)
seen.append(num)
for dup in duplicates:
print(dup)

Exercise 9: Split a list into two lists, one with the even numbers and one with the odd numbers

Write a program that reads the size of the list followed by the elements of the list and splits them into two lists: one containing all even numbers and one containing all odd numbers. Print both lists on separate lines.

Split Even and Odd

Checks: 0 times
Answer:
size = int(input())
numbers = []
for i in range(size):
numbers.append(int(input()))
even = []
odd = []
for num in numbers:
if num % 2 == 0:
even.append(num)
else:
odd.append(num)
print(even)
print(odd)

Exercise 10: Reverse a list using a loop

Write a program that reads the size of the list followed by the elements of the list and reverses the list using a loop (without using the reverse() method or slicing). Print the reversed list.

Reverse List

Checks: 0 times
Answer:
size = int(input())
numbers = []
for i in range(size):
numbers.append(int(input()))
reversed_list = []
for i in range(len(numbers) - 1, -1, -1):
reversed_list.append(numbers[i])
print(reversed_list)

Exercise 11: Sum of all inner lists

Given a list of lists, where each list contains numbers, write a program which reads the number of inner lists, then for each inner list reads the size of that inner list followed by its elements, and prints the sum of all the inner lists (each sum on a new line).

Sum of Inner Lists

Checks: 0 times
Answer:
n = int(input())
for i in range(n):
size = int(input())
inner_list = []
for j in range(size):
inner_list.append(int(input()))
total = 0
for num in inner_list:
total += num
print(total)

Course Progress

Section 22 of 61

Back to Course