Sign InNuggetsTutorials CodePadCheatsheet

Lists in Python

Tali is going out for shopping. She asks Andrew if his shopping list is ready. While she is waiting, she takes out her to-do list and makes a few updates. She also checks her book list to see if there are any books that she needs to borrow from the library.

Using a list is an effective way to organize data. Similar to our everyday list, a list in Python is an ordered sequence of values, which are called elements or items. It begins with an opening square bracket ( [ ) and ends with a closing square bracket( ] ). Elements in a list are separated with commas ( , ) and are ordered linearly starting at index zero. A list that contains no elements is called an empty list ([ ]). Andrew's shopping list has four items, with index numbers from 0 to 3.

list:   ['apple', 'cheese', 'tomato', 'egg'] 
index: 0 1 2 3

Elements in a list need not be of the same type. For example, Andrew can add how many items to buy in his list. Let's assign it to a variable called shopping. Now the list contains both strings and integers. We can even include another list as a list element, as shown in the books list in the example. We call lists with list elements nested lists.

shopping = ['apple', 3, 'cheese', 1, 'tomato', 4, 'egg', 12] 
books = [['The Hobbit', 'library', 'hold'], ['Holes', 'buy', 'Amazon'], ['Hatchet', 'library', 'due 10/2'], ['The BFG', 'own']]

Each element of a list can be accessed by putting its index after the list name in square brackets. Therefore, shopping[0] returns 'apple' and shopping[1] returns 3 and so on. Nested lists work the same way. What does books[1][0] return? How about books[2][2]?

© CS Wonders·Home·About·Contact·Classes·Gallery·Glossary·Fun Facts