Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Lists

A list holds many values in order, under one name: the marks of a class, the items in a shopping basket, the lines of a file. A list is written with square brackets and commas between the items. Lists are the most used collection in Python: they can grow and shrink, and their items can be changed.

Creating and reading lists

marks = [72, 85, 90, 64]
names = ["Asha", "Ravi", "Meera"]
mixed = [1, "two", 3.0, True]
empty = []
print(marks)
print(len(marks), len(empty))
print(names[0], names[-1])
print(marks[1:3])
Output
[72, 85, 90, 64]
4 0
Asha Meera
[85, 90]

Indexes and slices work exactly as for strings: the first item has index 0, -1 is the last one, and [1:3] takes items 1 and 2. A list can hold values of different types, although most lists hold values of one kind.

Changing a list

Unlike strings, lists are mutable: you can change them after they are created.

colours = ["red", "green", "blue"]
colours[1] = "yellow"
colours.append("purple")
print(colours)
print("blue" in colours, "pink" in colours)
colours[0:2] = ["black"]
print(colours)
Output
['red', 'yellow', 'blue', 'purple']
True False
['black', 'blue', 'purple']

append adds an item at the end. Assigning to a slice replaces a whole part of the list, even with a different number of items. The next topic, List Methods, shows many more ways to change lists.

Looping and totals

A for loop visits every item. For numbers, the built-in functions sum, min, max and sorted save writing loops yourself:

temps = [31, 28, 35, 30, 27]
for t in temps:
    print(t, "hot" if t > 30 else "fine")
print("Average:", sum(temps) / len(temps))
print("Highest:", max(temps), "Lowest:", min(temps))
print("Sorted:", sorted(temps))
Output
31 hot
28 fine
35 hot
30 fine
27 fine
Average: 30.2
Highest: 35 Lowest: 27
Sorted: [27, 28, 30, 31, 35]

Two names, one list

Assigning a list to another variable does not copy it: both names refer to the same list, so a change through one name is seen through the other. To get an independent copy, write copy = original.copy() or copy = original[:]. This surprises many learners, so remember it whenever a list seems to change "by itself".

Practice exercises

  1. Make a list of five friends' names and print the first, the last and how many there are.
  2. Replace the third name with another one and add a sixth name at the end.
  3. Make a list of prices and print the total, the cheapest and the most expensive.
  4. Show that b = a does not copy a list, then make a real copy and show the difference.