Skip to main content

Lists

Updated Oct 28, 2019 ·

Lists

Lists are ordered containers that hold multiple items. They are mutable, so you can add, remove, or update items easily.

In the example below, we create a cookies list of and manipulate it:

cookies = ["chocolate chip", "oatmeal", "sugar"]

# Add a new cookie
cookies.append("peanut butter")

# Combine with another list
more_cookies = ["ginger", "snickerdoodle"]
cookies.extend(more_cookies)

# Print the list
print(cookies)

Output:

['chocolate chip', 'oatmeal', 'sugar', 'peanut butter', 'ginger', 'snickerdoodle']

You can access a specific item by its index:

# Print the third cookie
print(cookies[2])

Output:

sugar

Common List Operations

  • Get the number of elements using len():

    fruits = ["apple", "banana", "cherry"]
    print(len(fruits))

    Output:

    3
  • Loop over each element in a sequence:

    for fruit in fruits:
    print(fruit)

    Output:

    apple
    banana
    cherry
  • Check if an element exists in a sequence:

    if "banana" in fruits:
    print("Found banana!")

    Output:

    Found banana!
  • Access an element by index:

    print(fruits[1])

    Output:

    banana
  • Get a slice of a sequence:

    print(fruits[0:2])  # first two elements
    print(fruits[:2]) # same as above
    print(fruits[1:]) # from second element to end

    Output:

    ['apple', 'banana']
    ['apple', 'banana']
    ['banana', 'cherry']
  • Loop over indexes and elements together with enumerate():

    for i, fruit in enumerate(fruits):
    print(i, fruit)

    Output:

    0 apple
    1 banana
    2 cherry
  • Replace an element at a specific index:

    fruits[1] = "blueberry"
    print(fruits)

    Output:

    ['apple', 'blueberry', 'cherry']
  • Add an element to the end with append():

    fruits.append("orange")
    print(fruits)

    Output:

    ['apple', 'blueberry', 'cherry', 'orange']
  • Insert an element at a specific position with insert():

    fruits.insert(1, "kiwi")
    print(fruits)

    Output:

    ['apple', 'kiwi', 'blueberry', 'cherry', 'orange']
  • Remove an element by index with pop():

    removed = fruits.pop(2)
    print(removed)
    print(fruits)

    Output:

    blueberry
    ['apple', 'kiwi', 'cherry', 'orange']
  • Remove the first occurrence of a value with remove():

    fruits.remove("kiwi")
    print(fruits)

    Output:

    ['apple', 'cherry', 'orange']
  • Sort the list in ascending order with sort():

    fruits.sort()
    print(fruits)

    Output:

    ['apple', 'cherry', 'orange']
  • Reverse the order of elements with reverse():

    fruits.reverse()
    print(fruits)

    Output:

    ['orange', 'cherry', 'apple']
  • Remove all elements with clear():

    fruits.clear()
    print(fruits)

    Output:

    []
  • Create a shallow copy with copy():

    fruits = ["apple", "banana"]
    fruits_copy = fruits.copy()
    print(fruits_copy)

    Output:

    ['apple', 'banana']
  • Append all elements from another list with extend():

    more_fruits = ["kiwi", "mango"]
    fruits.extend(more_fruits)
    print(fruits)

    Output:

    ['apple', 'banana', 'kiwi', 'mango']

List Comprehension

List comprehensions are a compact way to create new lists from existing sequences. They let you apply expressions and conditions in a single line.

  • Basic: Creates new list by evaluating the expression for each element in the sequence.

    squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]
  • With Condition: Adds elements to the new list only if the condition is met.

    evens = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]

For more information, please see List Comprehensions.