Thursday, April 16, 2015

Python - Lists and Tuples

Tuples are immutable (Cannot change). Use () brackets
Lists are mutable (can change).use [] brackets


ex for tuple:

v1=(1,2,3,4,5)
print(type(v1),v1)


O/P
<class 'tuple'> (1, 2, 3, 4, 5)


ex for list
v1=[1,2,3,4,5]
print(type(v1),v1)


O/P
<class 'list'> [1, 2, 3, 4, 5]

Since list is mutable you can append or insert values.

Ex:
v1=[1,2,3,4,5]
v1.append(8)
print(type(v1),v1)


O/P
<class 'list'> [1, 2, 3, 4, 5, 8]

Below example will insert 99 in third position

v1=[1,2,3,4,5]
v1.insert(2,99)
print(type(v1),v1)


O/P
<class 'list'> [1, 2, 99, 3, 4, 5]


Sequential with strings:

Below example displays 6th character of the string
Ex:
v1="This is my string"
print(type(v1),v1[5])


O/P
<class 'str'> i

Slicing the string

Below example displays values between 5th and 15th character
Ex:
v1="This is my string"
print(type(v1),v1[5:15])


O/P
<class 'str'> is my stri

Dictionary:

use {} for defining


Ex:
v1={'one':1, 'two':2, 'three':3,'four':4}
print(type(v1),v1)


O/P
<class 'dict'> {'four': 4, 'two': 2, 'three': 3, 'one': 1}


Below ex displays only keys 

v1={'one':1, 'two':2, 'three':3,'four':4}
print(type(v1),v1)
for i in v1:
    print(i)


O/P
<class 'dict'> {'two': 2, 'four': 4, 'one': 1, 'three': 3}
two
four
one
three


Below example will display both keys and values

Ex:
v1={'one':1, 'two':2, 'three':3,'four':4}
print(type(v1),v1)
for i in v1:
    print(i,v1[i])


O/P
<class 'dict'> {'two': 2, 'four': 4, 'three': 3, 'one': 1}
two 2
four 4
three 3
one 1

No comments:

Post a Comment