python lists data-structures

Lists in Python

Learning objectives

By the end of this pill you will be able to:

  • initialise lists ([], list()),
  • add/insert elements (append, insert, extend),
  • remove elements (remove, pop, clear),
  • iterate over and print values with for loops.

What is a list

A list is an ordered and mutable collection of elements enclosed in [ ]. It can contain numbers, strings or other lists.

numbers = [1, 2, 3, 4, 5]
words   = ["hello", "world", "python"]
mixed   = [1, "text", True, 3.14]

Initialising a list

You can create an empty list or one that is already populated.

empty = []
another_list = list()  # equivalent

grades = [6, 7, 8, 9, 10]  # already filled

Adding elements

Main methods for inserting new values.

append() — at the end of the list

grades = [6, 7, 8]
grades.append(9)
print(grades)   # [6, 7, 8, 9]

insert(pos, elem) — at a specific position

grades = [6, 7, 8, 9]
grades.insert(1, 5)      # inserts 5 at index 1
print(grades)            # [6, 5, 7, 8, 9]

extend(iterable) — adding multiple elements

grades = [6, 5, 7]
grades.extend([8, 9, 4, 3])
print(grades)  # [6, 5, 7, 8, 9, 4, 3]

Removing elements

remove(value) — removes the first occurrence

grades = [6, 5, 7, 8, 9, 4, 3]
grades.remove(5)
print(grades)  # [6, 7, 8, 9, 4, 3]

pop([index]) — removes and returns

grades = [6, 7, 8, 9, 4]
last = grades.pop()     # no index: removes the last element
print(last)             # 4
print(grades)           # [6, 7, 8, 9]

clear() — empties the list

grades = [6, 7]
grades.clear()
print(grades)  # []

Iterating over and reading elements

Direct for loop over elements

grades = [6, 7, 8, 9, 10]
for grade in grades:
    print(grade)

for loop with index

grades = [6, 7, 8, 9, 10]
for i in range(len(grades)):
    print(f"Element {i} = {grades[i]}")

Note: Indices start at 0. The last element is at len(list)-1.

Complete example

A program that creates a list, inserts and removes elements, then prints them.

numbers = []

# add elements
numbers.append(10)
numbers.append(20)
numbers.insert(1, 15)  # insert in the middle
print("List after insertions:", numbers)

# remove the last one
numbers.pop()
print("List after pop:", numbers)

# iterate over the list
print("Values in the list:")
for n in numbers:
    print(n)

Expected output:

List after insertions: [10, 15, 20]
List after pop: [10, 15]
Values in the list:
10
15

Summary

  • Creation: [], list()
  • Addition: append, insert, extend
  • Removal: remove, pop, clear
  • Reading: for loops over elements and indices