A list in python programming, is a collection of items assigned to one variable. A regular variable as you will recall, has just one value but a list has a list of values separated by commas, in a square bracket, assigned. You can imagine a variable to be one finger of banana (the value) hanging on the stem (whatever it is called haha) Where as a list is a bunch of bananas, all together on the stem.
ages = [1,2,3,4] print ages
The code above, assigns the list value [1,2,3,4] to a list variable named ages. In other languages such as C, C++ and Java, you are restricted to data types. You can only use one data type in an array (as it is called in those languages). However in python, you can mix up data types in a list, isn’t that awesome!
One common function we use with lists is
append(). Append as the name implies, appends an item to the list.
ages = [1,2,3,4] print ages # [1,2,3,4] ages.append('strange age') print ages # [1,2,3,4,strange age]
In lists, the positions of the items are known as their indexes. In the list called ages, we find 1 at index 0, 2 at index 1. Indexes start from 0, note this, it will go a long way to help you!
ages = [1,2,3,4] print ages # [1,2,3,4] print ages # 1 print ages # 3 #reassignment ages = 1 print ages #1 print ages # [1,1,3,4]
If you tried accessing an index that does not exist, it will throw an exception. Exceptions are errors that are thrown when a syntax that works (that’s why it’s not a syntax error) suddenly doesn’t work due to an unexpected result from your code.
Try printing ages
Try out different things with what you know so far on lists, post your findings in the comments. Now that you know about lists, we can go ahead and talk about for-loops. See ya in our next lesson. Cheers!