By Martin McBride, 2018-07-24
Tags: list index for loop append
Categories: python language beginning python


A list is a collection of items that are stored together as a group. It provides a way to keep a set of related items together.

About this lesson

In this lesson we will look at:

  • Creating lists
  • Accessing list elements
  • Looping through a list
  • Adding items to a list

Creating lists

You can create a list simply by enclosing a set of items in square brackets. Here is an example:

k = [9, 8, 7, 6]

This will create a list contains 4 items (the numbers 9, 8, 7 and 6). The items in a list are called its elements. When you print k, Python will print a representation of the whole list, which will look like:

[9, 8, 7, 6]

Lists can have any number of elements, and the elements can be of any type – they can be numbers, strings, or anything else – even other lists. The elements don't have to all be the same type.

Empty lists

It is possible to create an empty list, like this:

k = []

You might be wondering what is the use of an empty list? Well, Python lets you add extra elements to a list, so sometimes you might need to start with an empty list and build it up. An empty list can sometimes have a special meaning – for example, an empty to-do list means you have no tasks left to do.

Lists of repeating items

You can create a list of repeating items using the multiply operator, *. A common use of this is to create a list of zeros:

k = [0] *10

This will create a list like this:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

You can repeat a list of more than 1 item:

k = [4, 2] *3


[4, 2, 4, 2, 4, 2]

Accessing list elements

One of the things that make lists really useful is that your code can access individual list elements. List elements are numbered, starting at zero. So, in the following list of strings:

colors = ["red", "green", "blue"]

Element number 0 has the value red, element number 1 has the value green, and element number 2 has the value blue. The number of each element is called its index.

Reading elements

You can read individual elements in a list using [] notation:

colors = ["red", "green", "blue"]
s = colors[1]    # s takes the value "green"

In this case colors[1] fetches element 1 of the list – that is the second element (since the elements are numbered starting at 0). The print statement displays: green

Changing elements

You can change an element by setting its value:

colors = ["red", "green", "blue"]
colors[0] = "yellow"

This time we set element number 0 (the first element) to yellow. The print statement prints the whole list, which now looks like:

["yellow", "green", "blue"]

Finding the length of the list

If you need to find the length of a list, you can simply use the built-in len function:

colors = ["red", "green", "blue"]
n = len(colors)

Here n is set to the length of the list, which is 3 in this case.

Looping over a list

We have seen how to use a for loop with the range function:

for i in range(5):

This loop counts from 0 to 4. A for loop can be used to process each element in a list, one by one. Here is an example:

colors = ["red", "green", "blue"]
for color in colors:

In this case, the loop executes 3 times, with color equal to red, then blue, then green. The output of the program will be:


Doing calculations in a loop

Now we will use the loop to do something useful. We will add up the numbers in the list

numbers = [11, 24, 50, 3]
total = 0
for n in numbers:
    total = total + n

In this code we use the variable total to store a running total of the values in the list:

  • First we set total to zero before the list starts.
  • On each pass through the loop, we add n (the current loop value) to total.
  • When the loop ends, we print out the result.

This is just an example. Python has a function called sum that adds all the elements in a list. It is better to use that function, rather than creating a new one of your own

Adding elements

The append function can be used to add a value to the end of a list. For example:

numbers = [2, 4, 6, 8]
print(numbers)    # [2, 4, 6, 8, 7]

You can also add two lists, like this:

a = [10, 20, 30]
b = [6, 7]
c = a + b
print(c)    # [10, 20, 30, 6, 7]

See also

If you found this article useful, you might be interested in the book NumPy Recipes or other books by the same author.

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest