indusai.co

Lists

A list is an ordered collection that you can change. Lists are the workhorse of Python: if you have several related values, they probably belong in a list.

Creating a list

python
fruits = ["apple", "banana", "cherry"]
numbers = [3, 1, 4, 1, 5]
mixed = [1, "two", 3.0, True]
empty = []
print(fruits, numbers, mixed, empty)

Lists keep their order, allow duplicates and can hold any mix of types. list() also builds a list from any iterable:

python
print(list("hello"))
print(list(range(5)))

Length

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

Indexing

Positions start at 0. Negative positions count from the end.

python
fruits = ["apple", "banana", "cherry", "mango"]
print(fruits[0])
print(fruits[-1])
print(fruits[1:3])    # slice: index 1 up to (not including) 3
print(fruits[:2])
print(fruits[2:])

Asking for an index that does not exist raises IndexError.

Changing items

Unlike strings, lists are mutable.

python
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)

fruits[0:2] = ["kiwi", "lime"]   # replace a slice
print(fruits)

Adding items

python
fruits = ["apple", "banana"]
fruits.append("cherry")          # add to the end
fruits.insert(1, "avocado")      # insert at index 1
fruits.extend(["mango", "fig"])  # add several
print(fruits)

append(x) adds one item; extend(iterable) adds each item of the iterable. Mixing them up is a common bug:

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

Removing items

python
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")   # first matching value
print(fruits)

last = fruits.pop()       # remove and return the last item
print(last, fruits)

first = fruits.pop(0)     # remove by index
print(first, fruits)

del fruits[0]             # delete by index without returning
print(fruits)

fruits.clear()
print(fruits)

Checking membership

python
fruits = ["apple", "banana"]
print("apple" in fruits)
print("mango" in fruits)

Looping

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

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

Other useful operations

python
nums = [3, 1, 4, 1, 5, 9, 2]
print(nums.index(4))     # position of first 4
print(nums.count(1))
print(min(nums), max(nums), sum(nums))
print([1, 2] + [3, 4])   # concatenation
print([0] * 5)           # repetition

Practice

  1. Make a list of five cities. Replace the third one, append a sixth, then print the list and its length.
  2. Remove the first and last items of [10, 20, 30, 40, 50] using pop() and print what remains.
  3. Given marks = [72, 85, 61, 94], print the average using sum() and len().