Python Lists

Python lists store several items in a single variable, in order. Lists are written with square brackets, can hold any mix of types, and are mutable, so you can add, change and remove items after creating them. They are the most used collection in Python.

Create a List and Access Items

Items are indexed from 0. Negative indexes count from the end, and slices return a new list.

cities = ["Lahore", "London", "Madrid", "Dubai", "Toronto"]

print(cities)
print(len(cities))
print(cities[0], cities[-1])
print(cities[1:3])
['Lahore', 'London', 'Madrid', 'Dubai', 'Toronto']
5
Lahore Toronto
['London', 'Madrid']

Add Items to a List

append() adds one item at the end, insert() adds at a position, and extend() adds every item from another list.

cart = ["rice"]
cart.append("tea")
cart.insert(0, "flour")
cart.extend(["honey", "almonds"])
print(cart)

cart[1] = "brown rice"   # change an item
print(cart)
['flour', 'rice', 'tea', 'honey', 'almonds']
['flour', 'brown rice', 'tea', 'honey', 'almonds']

Remove Items from a List

remove() deletes the first item with a given value, pop() removes by index (the last item by default) and returns it, del deletes by index or slice, and clear() empties the list.

nums = [10, 20, 30, 20, 40]

nums.remove(20)
print(nums)

last = nums.pop()
print(last, nums)

del nums[0]
print(nums)
[10, 30, 20, 40]
40 [10, 30, 20]
[30, 20]

Sort a List

sort() sorts the list in place. sorted() returns a new sorted list and leaves the original alone. Both accept reverse=True and a key function.

prices = [18.75, 6.0, 22.0, 4.25]
prices.sort()
print(prices)

words = ["banana", "Kiwi", "apple"]
print(sorted(words))
print(sorted(words, key=str.lower))
print(sorted(words, key=len, reverse=True))
[4.25, 6.0, 18.75, 22.0]
['Kiwi', 'apple', 'banana']
['apple', 'banana', 'Kiwi']
['banana', 'apple', 'Kiwi']

Loop Through a List

A for loop visits every item. Use enumerate() when you also need the index.

languages = ["Python", "JavaScript", "SQL"]

for i, lang in enumerate(languages, start=1):
    print(i, lang)

print("Python" in languages)
print(languages.index("SQL"))
1 Python
2 JavaScript
3 SQL
True
2

Copy a List

Writing b = a does not copy a list; both names point to the same list, so changing one changes the other. Use a.copy(), list(a) or a[:] to make a real copy.

a = [1, 2, 3]
b = a
c = a.copy()

a.append(4)
print(b)
print(c)
[1, 2, 3, 4]
[1, 2, 3]

Useful List Functions

  • len(list), sum(list), min(list), max(list)
  • list.count(x) counts how many times x appears
  • list.reverse() reverses the list in place
  • list1 + list2 joins lists; list * 3 repeats it

Frequently asked questions

How do I add an item to a list in Python?

Use append(item) to add one item to the end, insert(index, item) to add it at a position, or extend(other_list) to add several items.

What is the difference between sort() and sorted()?

list.sort() changes the original list and returns None. sorted(list) returns a new sorted list and works on any iterable, leaving the original unchanged.

How do I get the length of a list in Python?

Call len(my_list). It returns the number of items in the list.

Can a Python list contain different data types?

Yes. A list can mix strings, numbers, booleans and even other lists, although most real lists hold items of one kind.