Lists & Dictionaries

Term: [], {} in Python

A list is a value that contains many items in an ordered sequence, and is written like this, [‘fish’, ‘book’, ‘British’]. Each term (fish, book & British) in the list are typed with quote characters (‘ ’) and separated by ‘,’. The list begins and ends with square bracket ([]). The list is like a shopping list, and a dictionary is more complicated, like a book or a dictionary.

Now, I have a list named beasts, and type them all on the interactive shell (which shows >>> on the screen).

>>> beasts = [‘dodo’, ‘griffin’, ‘platypus’, ‘phoenix’]

>>> beasts[0]

This beasts list contains four beasts: dodo, griffin, platypus and phoenix. And, one beast follows antoher beast. If you type >>>beasts[0], the ‘dodo’ will show on the screen. The integer inside the square brackets ([0], [1], etc.) that follows the list is called “index”.
Q1: What are indexes for dodo, griffin, platypus and phoenix in the list of beasts? Ans: 0, 1, 2, 3
Q2: There are also negative indexes such as -1, -2, -3 and so on. And, which beast does beasts[-1] refer to in this list of beasts?

Be careful to type this and see what happens.

>>> beasts[1], beasts[2], beasts[3]

(‘griffin’, ‘platypus’, ‘phoenix’)

’Cause any thing in a list can be written in a sentance, try to type this sentance on the interactive shell:

>>> ‘The ’ + beasts[0] + ‘ and ’ + beasts[3] + ‘ are friends.’

‘The dodo and phoenix are friends.’

The strings, The, and, are friends are typed with quote characters (‘ ’), and beasts[0] and beasts[3] are not.

A box in a box, and a list in a list is a list (XD). A list can be put into another list; you also can put many lists in a list. Type like this:

>>> BeastsInHouse = [[‘dodo’, ‘griffin’, ‘platypus’, ‘phoenix’], [1, 2, 3, 4]]

There are two lists in BeastsInHouse. The first one is [‘dodo’, ‘griffin’, ‘platypus’, ‘phoenix’]. The second one is [1, 2, 3, 4] (*These numbers donot have to be typed with ‘’.)
Then, type BeastsInHouse[0] on the interactive shell, it displays the first list. The second list can be found out with BeastsInHouse[1].

>>> BeastsInHouse[0]

[‘dodo’, ‘griffin’, ‘platypus’, ‘phoenix’]

>>> BeastsInHouse[1]

[1, 2, 3, 4]

The BeastsInHouse[0][1] refers to the second thing of first list.

>>> BeastsInHouse[0][1]


Like what you read? Give Hui-Ling Lee a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.