← Python from Scratch Lesson 35 of 78 · 10 XP

Lists

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A list (list) holds several values in order. It is written in square brackets:

nums = [5, 2, 8]
names = ["Anya", "Borya"]
mixed = [1, "two", 3.0]      # you can mix types, but usually people don't

Indices and slices work as with strings: nums[0] → 5, nums[-1] → 8, nums[1:] → [2, 8].

Unlike strings, lists are mutable:

nums.append(10)      # add to the end         → [5, 2, 8, 10]
nums.insert(0, 1)    # insert at an index     → [1, 5, 2, 8, 10]
nums.remove(8)       # remove a value         → [1, 5, 2, 10]
last = nums.pop()    # take out the last one  → last = 10
nums[0] = 99         # replace an item
nums.sort()          # sort in place

Useful functions: len(nums), sum(nums), min(nums), max(nums), sorted(nums) (returns a new sorted list).

About "arrays". Other languages have arrays of a fixed size and a single type. In Python the list plays that role. The array module and the numpy library give you "real" arrays of numbers — you need them when there are millions of values.

Task. Write a function stats(nums) that returns a list of three numbers: the minimum, the maximum and the average rounded to 2 decimal places. stats([1, 2, 3, 4]) → [1, 4, 2.5].

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.