Pretty much every programming language has a way to group a whole bunch of items together into a single group, or as Python calls them list. Other languages have similar things called arrays, but they, for the most part, generally work the same whether you’re learning Java , Python, C or some other language.
The give away, in most languages is when you see brackets : [] .
The code set below initializes 3 different lists:
1 2 3 |
animals = ["penguin", "cow", "camel"] grades = [ 5, 10, 2.2] stuff = ["Pyth", 3.14 , "on", True] |
The first list stores animals stores several Strings
The second list , grades , several numbers.
The third list, stuff, stores a different types of data–some strings, a floating point number 3.14, and its final element is a boolean value True .
How do we refer to specific elements in a list?
Well, we use bracket notation. Let’s look at the animals list. If we run the code below:
1 2 3 4 5 |
animals = ["penguin", "cow", "camel"] print( animals[0] ) print( animals[1] ) print( animals[2] ) |
You will see the output below.
Yes, lists start counting at zero in python and in many other languages so we refer to the first element in animals as animals[0] and the second element as animals[1] .
Below is a diagram of the list. We call the location of the element in the list its index .
so, what happens if we try to print something with an index value of 3 like this
1 2 |
animals = [ "penguin" , "cow", "camel"] print (animals[3]) |
So, yes , Python spits out an error message when you try to go to an index that does not exist. In technical speak, we say that it throws an error
Below is a diagram of each element at each index.