Module 3 - Section 2 - Lists

3.2.2 - Lists

So what should i do if i want to create a shopping list? Copy the following command and test it.

>>> my_shopping_list = ["apples","bananas","carrots"] 

>>> print(my_shopping_list)

The items in the list are numbered starting from 0 (as we mentioned in programming we usually start from 0).

So  the 0 item in my_shopping_list is "apples"

      the 1 item is "bananas"

and the 2 item is "carrots"

Try the following :

>>> print(my_shopping_list[0]) # in print we use parenthesis () and in lists square brackets [])

>>> print(my_shopping_list[1])

>>> print(my_shopping_list[2])

>>> print(my_shopping_list[3])

In the last example there is an error :

Traceback (most recent call last):

  File "<pyshell>", line 1, in <module>

IndexError: list index out of range

because myshoppinglist does not have an item indexed 3

we can change an item in list :

>>> my_shopping_list[0] = "apricots"

>>> print(my_shopping_list)

And we can iterate (loop) through a list. Copy the following code to Thonny and save it as list_friends.py inside your working folder:

my_friends = ["Jim", "John", "Jack", "Jane"] for item in my_friends: print (item)

We can view the number of items in a list with command len.

>>> len(my_friends)

and we can add items to a list :

>>> my_friends.append("Joe")

>>> print(my_friends)

Our list has 5 items now. Check its length.