Python List – Beginner’s Guide and Sample Code

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:

 

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:

You will see the output below.

list-output

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 . python-list-with-index-diagram

so, what happens if we try to print something with an index value of 3 like this

python-index-out-of-range-message

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.

plython-list-index-out-of-bounds-diagram