Tuesday, December 23, 2014

Lists in Python

We will now see lists creation in python

variableName = []
# This defines that the variableName is a list.

variableName = [2,3,4,5,"Hello",7]
#after seeing above example you can be sure that there is no limitation on data type of a list
#same list contain variables as well as a string

>>>print variableName
[2,3,4,5,'Hello',7]

>>>

>>> print variableName[]
#this will give you an error
>>>print variableName[0]
2
>>>print variableName[2]
4
>>>print variableName[-1]
7
>>>print variableName[5]
7
>>>print variableName[-2]
'Hello'
>>>print variableName[4]
'Hello'
>>>print variableName[-6]
2
>>>print variableName[6]
#this will give you error as we have no data items at 7th location in the list.
>>>print variableName[3:5]
[5,'Hello']
#':' refers to 'to'. 3:5 refers from index location 3 to index location 5. last index location is excluded from the list.

''' Thus you can infer that in python we can access the list from both sides.
From front side the index starts from 0 then 1,2,3 and so on.
From rear side the index starts from -1 then -2,-3,-4 and so on
'''

No comments:

Post a Comment