I1 · Python Programming for AI

Lists

A list is an ordered, changeable collection of items, written in square brackets, such as [72, 85, 64]. Items are accessed by index from 0, can be of any type, and can be added, removed, changed and sorted.

12 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

How do you keep the marks of fifty students in one place?

A list is an ordered, changeable collection of items, written in square brackets, such as [72, 85, 64]. Items are accessed by index from 0, can be of any type, and can be added, removed, changed and sorted.

In simple words

A list is a row of numbered boxes in one variable. marks[0] is the first box. marks.append(90) adds a box at the end. len(marks) counts the boxes. sum(marks) / len(marks) is the average. Unlike a string, you can change any box.

Why it matters

Datasets are collections: rows of data, lists of words, batches of images. Lists are Python's basic collection, and NumPy arrays and pandas columns, used throughout AI, behave in similar ways.

How it works

OperationExampleResult for marks = [72, 85, 64]
Accessmarks[1]85
Changemarks[2] = 70[72, 85, 70]
Add to endmarks.append(90)[72, 85, 64, 90]
Remove a valuemarks.remove(85)[72, 64]
Sortsorted(marks)[64, 72, 85]
Length, total, largestlen, sum, max3, 221, 85

In code

A marks list with average, topper and a sorted copy.

marks_list.py
names = ["Aarav", "Meera", "Kabir", "Sana"]
marks = [72, 91, 64, 85]

print("Average:", sum(marks) / len(marks))
best = max(marks)
print("Topper:", names[marks.index(best)], "with", best)

marks.append(78)
names.append("Ishaan")
print("After adding Ishaan:", marks)
print("Sorted copy:", sorted(marks))
print("Original order kept:", marks)
print("Highest three:", sorted(marks, reverse=True)[:3])

Output

Average: 78.0
Topper: Meera with 91
After adding Ishaan: [72, 91, 64, 85, 78]
Sorted copy: [64, 72, 78, 85, 91]
Original order kept: [72, 91, 64, 85, 78]
Highest three: [91, 85, 78]

Try it yourself

Predict the list

Start each time from nums = [3, 1, 2]. What does each operation give?

  • nums.append(5); nums
  • sorted(nums)
  • nums[0] = 9; nums
  • len(nums)
  • nums[-1]

Common mistakes

  • Writing x = x.sort(), which sets x to None.
  • Using an index that is too big: IndexError.
  • Copying with b = a and being surprised that changing b changes a. Use a.copy().

Check yourself

Question 1

1. For a = [5, 6, 7], what is a[1]?

Question 2

2. Which adds an item to the end?

Question 3

3. What does sorted([3, 1, 2]) return?

Summary

  • Lists are ordered, changeable collections in square brackets.
  • append, remove, sort, len, sum and max cover most needs.
  • sorted() returns a new list; .sort() changes the original.

Finished reading?

Sources: Python docs: Data Structures