Showing posts with label list. Show all posts
Showing posts with label list. Show all posts

Wednesday, December 24, 2014

Tuples

TUPLES:

In many ways, tuples are similar to the lists.

Difference between tuples and List:
1. Tuples are immutable while List are mutables.
    Immutable means that we can not modify the tuples like appending an element, inserting an item         an item at a particular position or deleting one or more elements. These are the operations which         can be done on lists.
2. Tuples are heterogeneous data structure while lists are homogeneous sequence.
    It means tuples are sequence of different kind of items while lists are sequence of same kind of           items.

>>>a=1,2,3,4,5,6
>>>a
(1,2,3,4,5,6)
>>>

however a.append(5) or a[3]=5 kind of statements will give you errors because as mentioned tuples are immutable that is they can not be modified.

but the printing of elements of tuples are similar as printing method of lists.

>>>print a[0]
1
>>>print a[:3]
(1,2,3)
>>>print a[::-1]
(6,5,4,3,2,1)


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
'''