Python : Crash Course Part 4 – Lists

Lists in python are a sequence of elements/objects
( character strings, numeric variable etc. )
enclosed within a square bracket and separated by a comma.

In [1]:[1,2,3]
In [2]:my_list = ['a','b','c']

If we need to add more character to the end of the list we use the append method as shown below :

In [3]:my_list.append('d')
In [4]:my_list

Note that to append a character at the end of the list we use the curve bracket and not a square bracket in the append method.

Even the list is indexed and will behave exactly like how we discussed indexing on the strings. If we have to grab the first item in the list it would be :

In [6]:my_list[0]

If I want to update ‘d’ as ‘data’ in my list I will have to :

In [7]:my_list[3] ='data'
In [8]:my_list

Note that if I have to update the 4th character I have to update the 3rd index position.

Nested Lists –

Python enables to have a list within a list as shown below

In [9] :nested = [1,2,[3,4]]
In [10]:nested

In order to retrieve elements within a nested list we can use the below syntax :

In [12]:nested[2][1]

The first square bracket above shifts pointer to the second list which is [3,4]. the next square bracket points to index number 1 of the nested list and retrieves 4.

Lets now move on to dictionaries in python.