Creating and Indexing Lists

40 min read Working with Lists

This is a free course. Log in to run the code exercises and track your progress.

Creating and Indexing Lists

A list stores many values, in order, in one variable. It is written in square brackets, and the values can be of any type. Lists use the same indexing and slicing as strings, but unlike strings they are mutable: an element can be changed in place.

marks = [78, 91, 65, 88, 70]
print(marks[0], marks[-1])  # 78 70
marks[2] = 68               # change the third mark
print(marks[1:3])           # [91, 68]
print(len(marks), sum(marks), max(marks), min(marks))   # 5 395 91 68

To read a whole line of numbers into a list: nums = list(map(int, input().split())). A for loop visits every element: for m in marks:.

Python exercise

Read the marks of a student in several subjects from one line. Print Total: , Highest: and Average: (two decimals) on three lines.

marks = list(map(int, input().split()))
total = 0
highest = 0
print("Total:", total)
print("Highest:", highest)
print(f"Average: {0:.2f}")

Log in to edit and run this code.