List can be seen as a collection: they can hold many variables. List resemble physical lists, they can contain a number of items.

A list can have any number of elements. They are similar to arrays in other programming languages. Lists can hold all kinds of variables: integers (whole numbers), floats, characters, texts and many more.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Example

Empty list

Lets create an empty list. To define an empty list you should use brackets.
Brackets is what tells Python that the object is a list.

list = []

Lists can hold both numbers and text. Regardless of contents, they are accessed in the same fashion.

To access a list add the id between the brackets, such as list[0], list[1] and so on.

Define list

An empty list was defined above. Lists can contain all kinds of data.
You can create numeric lists like this:

ratings = [ 3,4,6,3,4,6,5 ]

Lists can contain strings or characters:

ratings = [ 'A','A','B','A','C','A' ]

To output simple print them

print(ratings)

You can interact item by item using a for loop.

Access list items

You can access a list item by using brackets and its index. Python starts counting at zero, that means the first element is zero.

Why count from zero?

Computer languages used to count from zero. At the time when programming languages were first created, it made sense to count from zero. These days it would just be strange to change that tradition.

To get the first item, simply add the brackets and a zero after the list name.

print(rating[0])

Every other element can be accessed by the incremental numbers, to print the second item you’d use (1), to print the thrid item you’d use (2).

print(rating[1])

List example

Type the code below and run it:

#!/usr/bin/python

list = [ "New York", "Los Angles", "Boston", "Denver" ]

print(list) # prints all elements
print(list[0]) # print first element

list2 = [1,3,4,6,4,7,8,2,3]

print(sum(list2))
print(min(list2))
print(max(list2))
print(list2[0])
print(list2[-1])

This should output:

list

Exercise

  1. Make a program that displays the states in the U.S.

    states = [ 'Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming' ] 

  2. Display all states starting with the letter M

Download answers