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 Programming Course & Exercises
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.
1 | 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:
1 | ratings = [ 3,4,6,3,4,6,5 ] |
Lists can contain strings or characters:
1 | ratings = [ 'A','A','B','A','C','A' ] |
To output simple print them1
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.
1 | 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).
1 | print(rating[1]) |
List example
Type the code below and run it:1
2
3
4
5
6
7
8
9
10
11
12
13
14#!/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:
If you are a beginner, then I highly recommend this book.
Exercise
Make a program that displays the states in the U.S.
1
2states = [ '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' ]
Display all states starting with the letter M