Today we learn about lists!

Remember arrays from C++ ? 😀  If not, no worries – just think of any ‘To do’ list or  ‘shopping  list’!  A list  is  a collection of variables – and there is no limit in the number of variables!  You can have a list of two items to a thousand items and beyond!

Also,  a list can have any type of variables in it – an integer list, a string list or even mix and match lists (lists containing different variable type).  Because you do not have to explicitly define variables in Python like many other language – making lists  is very easy – just throw in whatever variables you need to directly in your new list!

  1. Let’s create some lists.  Type and run:

list1 = [3,2,1]

          print(list1)

PPG = [ ‘Sugar’, ‘Spice’, ‘Everything Nice’]

print(PPG)

MR = [‘Mushfiqur Rahman’, ‘Bangladeshi’, 33, 36.31]

print (MR)

2. We can add more items to an already created list using ‘append()’

PPG.append(‘Chemical X’)

print(PPG)

list1.append(“Let’s go!”)

print(list1)

This fancy  ‘thing1.thing2()’   system is a cool stuff in Python where thing 1 is called an ‘object’ or ‘class’ and thing2 is called a method.  So the general format  is    object.method().      We use ‘methods’  to modify an ‘object’.  We will learn more about these later. 

3. We can also create a list the following way.   This may look cumbersome – but this is for the times you do not know what are the items that are  going to be in a list from the beginning. So you  start with an empty list and  you just add data as you go.

chaptersCompleted = []

chaptersCompleted.append(‘print’)

chaptersCompleted.append(‘variables’)

chaptersCompleted.append(‘strings’)

print(‘I completed the following topics in first week:  %s’ %chaptersCompleted)

4. How do we extract an item from the list?  We specify the index in square brackets!  Please note that indexing starts form 0.  So first item in a list is positioned at index 0, second item at index 1, third item at index 2 and so on.

secondNumber = list1[1]

print(secondNumber)

Print(‘The age of Mushfiqur Rahim is %d’  %(MR[2]))

5. Try accessing an index that is bigger that a list’s size. 

print(PPG[10])

What happens?

This is one of the most common problems  because we often have an n-size list and then use list[n]   to extract the last item and get an out-of-range error.  But the last item is actually at n-1!

6. To get the size of your list ( number of items in your list) you can use the function len().  

print(len(PPG))

print(PPG)

Note that len() is a function (has the capacity to take in arguments) ,  not a method ( methods come after a ‘dot’ and takes no arguments).  We will do functions later.

Exercise

Make a list of four or five or six  shows you plan  to watch and print the following .

I’ve prepared a list of  {# of items in your list}  shows to watch and am very excited to start with {first item in your list}