Code of the Day

Lists — collections of values

Store many values in one place, access them by position, and loop over them with ease.

First Steps9 min read
By the end of this lesson you will be able to:
  • Create a list and access elements by index
  • Add and remove elements with append and pop
  • Iterate over every element in a list with a for loop

Every variable you have used so far holds exactly one value. That works fine for a single temperature or a person's name, but most programs deal with collections: a list of students, a set of prices, the words in a sentence. Creating a separate variable for each item is unworkable.

Python's list stores an ordered sequence of values in a single variable. You can have as many items as you need, access any one by its position, add new items, and loop over the whole collection with a for loop.

Creating a list and indexing

A list is written with square brackets, items separated by commas:

fruits = ["apple", "banana", "cherry"]

Access an individual item by its index — its position, counting from zero:

print(fruits[0])   # apple
print(fruits[1])   # banana
print(fruits[2])   # cherry

Python counts from 0. The first item is index 0, the second is index 1, and so on. This is a universal convention shared by nearly every programming language.

Negative indices count from the end:

print(fruits[-1])  # cherry  (last item)
print(fruits[-2])  # banana  (second to last)

Length with len()

len() tells you how many items a list contains:

print(len(fruits))   # 3

Adding and removing items

append adds an item to the end:

fruits.append("date")
print(fruits)   # ['apple', 'banana', 'cherry', 'date']

pop removes and returns the last item (or the item at an index you specify):

last = fruits.pop()
print(last)     # date
print(fruits)   # ['apple', 'banana', 'cherry']
Python — editable, runs in your browser

Iterating over a list

A for loop works directly on lists — you do not need indices:

scores = [88, 92, 75, 100, 60]

for score in scores:
    if score >= 90:
        print(score, "— excellent!")
    else:
        print(score)

When you do need the index and the value together, use enumerate:

for i, fruit in enumerate(fruits):
    print(i, fruit)

Lists can hold any type, and can even mix types — [1, "hello", True] is a valid Python list. In practice, lists are most useful (and most readable) when all items are the same type.

Exercise

Filter positive numbersPython

Write a function only_positives(nums) that takes a list of numbers and returns a new list containing only the numbers that are greater than 0.

only_positives([1, -2, 3])[1, 3]only_positives([-1, -5])[]

Where to go next

Next: the First steps lab — three exercises that combine everything you have learned so far into real mini-programs.

Finished reading? Mark it complete to track your progress.

On this page