List, Tuple Data Types - Python
List, Tuple Data Types - Python
DATA STRUCTURE
֍ If we want to represent a group of individual objects as a single entity where insertion
order preserved and duplicates are allowed, then we should go for List.
֍ insertion order preserved.
֍ duplicate objects are allowed.
֍ heterogeneous objects are allowed.
֍ List is dynamic because based on our requirement we can increase the size and
decrease the size.
֍ In List the elements will be placed within square brackets and with comma seperator.
֍ We can differentiate duplicate elements by using index and we can preserve insertion
order by using index. Hence index will play very important role.
֍ Python supports both positive and negative indexes. +ve index means from left to
right where as negative index means right to left.
[10,"A","B",20, 30, 10]
-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5
֍ List objects are mutable.i.e we can change the content.
1) list=[]
2) print(list)
3) print(type(list))
4)
5) []
6) <class 'list'>
2) If we know elements already then we can create list as follows list = [10, 20, 30, 40]
1) list=eval(input("Enter List:"))
2) print(list)
3) print(type(list))
D:\Python_classes>py test.py
Enter List:[10,20,30,40]
[10, 20, 30, 40]
<class 'list'>
4) With list() Function:
1) l=list(range(0,10,2))
2) print(l)
3) print(type(l))
D:\Python_classes>py test.py
[0, 2, 4, 6, 8]
<class 'list'>
Eg:
1) s="HELLO"
2) l=list(s)
3) print(l)
D:\Python_classes>py test.py
['H', 'E, 'L', 'L', '0']
D:\Python_classes>py test.py
['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']
<class 'list'>
Note: Sometimes we can take list inside another list, such type of lists are called nested
lists.
[10, 20, [30, 40]]
1) By using Index:
֍ List follows zero based index. ie index of first element is zero.
֍ List supports both +ve and -ve indexes.
֍ +ve index meant for Left to Right
֍ -ve index meant for Right to Left
֍ list = [10, 20, 30, 40]
-4 -3 -2 -1
10 20 30 40
list
0 1 2 3
֍ print(list[0]) 10
֍ print(list[-1]) 40
֍ print(list[10]) IndexError: list index out of range
1) n=[1,2,3,4,5,6,7,8,9,10]
2) print(n[2:7:2])
3) print(n[4::2])
4) print(n[3:7])
5) print(n[8:2:-2])
6) print(n[4:100])
Output
D:\Python_classes>py test.py
[3, 5, 7]
[5, 7, 9]
[4, 5, 6, 7]
[9, 7, 5]
[5, 6, 7, 8, 9, 10]
List vs Mutability:
Once we creates a List object, we can modify its content. Hence List objects are mutable.
1) n=[10,20,30,40]
2) print(n)
3) n[1]=777
4) print(n)
D:\Python_classes>py test.py
[10, 20, 30, 40]
[10, 777, 30, 40]
D:\Python_classes>py test.py
0
1
2
3
4
5
6
7
8
9
10
D:\Python_classes>py test.py
0
2
4
6
8
10
D:\Python_classes>py test.py
A is available at positive index: 0 and at negative index: -3B
is available at positive index: 1 and at negative index: -2C is
available at positive index: 2 and at negative index: -1
Important Functions of List:
I. To get Information about List:
1) len():
Returns the number of elements present in the list
Eg: n = [10, 20, 30, 40]
print(len(n) 4
2) count():
It returns the number of occurrences of specified item in the list
1) n=[1,2,2,2,2,3,3]
2) print(n.count(1))
3) print(n.count(2))
4) print(n.count(3))
5) print(n.count(4))
D:\Python_classes>py test.py
1
4
2
0
3) index():
Returns the index of first occurrence of the specified item.
1) n = [1, 2, 2, 2, 2, 3, 3]
2) print(n.index(1)) 0
3) print(n.index(2)) 1
4) print(n.index(3)) 5
5) print(n.index(4)) ValueError: 4 is not in list
Note: If the specified element not present in the list then we will get ValueError.Hence
before index() method we have to check whether item present in the list or not by using in
operator.
print( 4 in n) False
II. Manipulating Elements of List:
1) append() Function:
We can use append() function to add item at the end of the list.
1) list=[]
2) list.append("A")
3) list.append("B")
4) list.append("C")
5) print(list)
D:\Python_classes>py test.py
['A', 'B', 'C']
Eg: To add all elements to list upto 100 which are divisible by 10
1) list=[]
2) for i in range(101):
3) if i%10==0:
4) list.append(i)
5) print(list)
D:\Python_classes>py test.py
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
2) insert() Function:
To insert item at specified index position
1) n=[1,2,3,4,5]
2) n.insert(1,888)
3) print(n)
D:\Python_classes>py test.py
[1, 888, 2, 3, 4, 5]
1) n=[1,2,3,4,5]
2) n.insert(10,777)
3) n.insert(-10,999)
4) print(n)
D:\Python_classes>py test.py
[999, 1, 2, 3, 4, 5, 777]
Note: If the specified index is greater than max index then element will be inserted at last
position. If the specified index is smaller than min index then element will be inserted at
first position.
3) extend() Function:
To add all items of one list to another list
l1.extend(l2)
all items present in l2 will be added to l1
1) order1=["Chicken","Mutton","Fish"]
2) order2=["RC","KF","FO"]
3) order1.extend(order2)
4) print(order1)
D:\Python_classes>py test.py
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
1) order = ["Chicken","Mutton","Fish"]
2) order.extend("Mushroom")
3) print(order)
D:\Python_classes>py test.py
['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
remove() Function:
We can use this function to remove specified item from the list.If the item present
multiple times then only first occurrence will be removed.
1) n=[10,20,10,30]
2) n.remove(10)
3) print(n)
D:\Python_classes>py test.py
[20, 10, 30]
If the specified item not present in list then we will get ValueError
1) n=[10,20,10,30]
2) n.remove(40)
3) print(n)
Note: Hence before using remove() method first we have to check specified element
present in the list or not by using in operator.
4) pop() Function:
It removes and returns the last element of the list.
This is only function which manipulates list and returns some element.
1) n=[10,20,30,40]
2) print(n.pop())
3) print(n.pop())
4) print(n)
D:\Python_classes>py test.py
40
30
[10, 20]
1) n = []
2) print(n.pop()) IndexError: pop from empty list
Note:
1) pop() is the only function which manipulates the list and returns some value
2) In general we can use append() and pop() functions to implement stack datastructure
by using list,which follows LIFO(Last In First Out) order.
In general we can use pop() function to remove last element of the list. But we can use to
remove elements based on index.
1) n = [10,20,30,40,50,60]
2) print(n.pop()) 60
3) print(n.pop(1)) 20
4) print(n.pop(10)) IndexError: pop index out of range
Differences between remove() and pop()
remove() pop()
1) We can use to remove special element 1) We can use to remove last element
from the List. from the List.
2) It can’t return any value. 2) It returned removed element.
3) If special element not available then we 3) If List is empty then we get Error.
get VALUE ERROR.
Note: List Objects are dynamic. i.e based on our requirement we can increase and
decrease the size.
1) reverse():
We can use to reverse() order of elements of list.
1) n=[10,20,30,40]
2) n.reverse()
3) print(n)
D:\Python_classes>py test.py
[40, 30, 20, 10]
2) sort():
In list by default insertion order is preserved. If want to sort the elements of list
according to default natural sorting order then we should go for sort() method.
1) n = [20,5,15,10,0]
2) n.sort()
3) print(n) [0,5,10,15,20]
4)
5) s = ["Dog","Banana","Cat","Apple"]
6) s.sort()
7) print(s) ['Apple','Banana','Cat','Dog']
Note: To use sort() function, compulsory list should contain only homogeneous elements.
Otherwise we will get TypeError
1) n=[20,10,"A","B"]
2) n.sort()
3) print(n)
Note: In Python 2 if List contains both numbers and Strings then sort() function first sort
numbers followed by strings
1) n=[20,"B",10,"A"]
2) n.sort()
3) print(n)# [10,20,'A','B']
1) n = [40,10,30,20]
2) n.sort()
3) print(n) [10,20,30,40]
4) n.sort(reverse = True)
5) print(n) [40,30,20,10]
6) n.sort(reverse = False)
7) print(n) [10,20,30,40]
1) x=[10,20,30,40]
2) y=x 10 20 30 40
x
3) print(id(x)) y
4) print(id(y))
The problem in this approach is by using one reference variable if we are changing
content, then those changes will be reflected to the other reference variable.
4) print(x) [10,777,30,40]
10 20 30 40
x
10 20 30 40
777
y
2) By using copy() Function:
1) x = [10,20,30,40]
2) y = x.copy()
3) y[1] = 777
4) print(x) [10, 20, 30, 40]
5) print(y) [10, 777, 30, 40]
10 20 30 40
x
10 20 30 40
777
y
Note: To use + operator compulsory both arguments should be list objects, otherwise we
will get TypeError.
Eg:
c = a+40 TypeError: can only concatenate list (not "int") to list.
c = a+[40] Valid
Note: Whenever we are using comparison operators (==, !=) for List objects then the
following should be considered
1) The Number of Elements
2) The Order of Elements
3) The Content of Elements (Case Sensitive)
Note: When ever we are using relational Operators (<, <=, >, >=) between List Objects,
only 1ST Element comparison will be performed.
1) x = [50, 20, 30]
2) y = [40, 50, 60, 100, 200]
3) print(x>y) True
4) print(x>=y) True
5) print(x<y) False
6) print(x<=y) False
Eg:
Membership Operators:
We can check whether element is a member of the list or not by using memebership
operators.
1) in Operator
2) not in Operator
1) n=[10,20,30,40]
2) print (10 in n)
3) print (10 not in n)
4) print (50 in n)
5) print (50 not in n)
Output
True
False
False
True
clear() Function:
We can use clear() function to remove all elements of List.
1) n=[10,20,30,40]
2) print(n)
3) n.clear()
4) print(n)
Output
D:\Python_classes>py test.py
[10, 20, 30, 40]
[]
Nested Lists:
Sometimes we can take one list inside another list. Such type of lists are called nested
lists.
1) n=[10,20,[30,40]]
2) print(n)
3) print(n[0])
4) print(n[2])
5) print(n[2][0])
6) print(n[2][1])
Output
D:\Python_classes>py test.py
[10, 20, [30, 40]]
10
[30, 40]
30
40
Note: We can access nested list elements by using index just like accessing multi
dimensional array elements.
1) n=[[10,20,30],[40,50,60],[70,80,90]]
2) print(n)
3) print("Elements by Row wise:")
4) for r in n:
5) print(r)
6) print("Elements by Matrix style:")
7) for i in range(len(n)):
8) for j in range(len(n[i])):
9) print(n[i][j],end=' ')
10) print()
Output
D:\Python_classes>py test.py
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
List Comprehensions:
It is very easy and compact way of creating list objects from any iterable objects
(Like List, Tuple, Dictionary, Range etc) based on some condition.
D:\Python_classes>py test.py
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[2, 4, 8, 16, 32]
[4, 16, 36, 64, 100]
1) words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
2) l=[w[0] for w in words]
3) print(l)
1) num1=[10,20,30,40]
2) num2=[30,40,50,60]
3) num3=[ i for i in num1 if i not in num2]
4) print(num3) [10,20]
5)
6) common elements present in num1 and num2
7) num4=[i for i in num1 if i in num2]
8) print(num4) [30, 40]
D:\Python_classes>py test.py
Enter the word to search for vowels:helloworld
['e’,’o’]
The number of different vowels present in helloworld is 2
TUPLE
DATA STRUCTURE
1) Tuple is exactly same as List except that it is immutable. i.e once we creates Tuple
object, we cannot perform any changes in that object.
2) Hence Tuple is Read only version of List.
3) If our data is fixed and never changes then we should go for Tuple.
4) Insertion Order is preserved
5) Duplicates are allowed
6) Heterogeneous objects are allowed.
7) We can preserve insertion order and we can differentiate duplicate objects by using
index. Hence index will play very important role in Tuple also.
8) Tuple support both +ve and -ve index. +ve index means forward direction (from left to
right) and -ve index means backward direction (from right to left)
9) We can represent Tuple elements within Parenthesis and with comma seperator.
10) Parenethesis are optional but recommended to use.
1) t=10,20,30,40
2) print(t)
3) print(type(t))
4)
5) Output
6) (10, 20, 30, 40)
7)
8) <class 'tuple'>
9) t=()
10) print(type(t) tuple
Note: We have to take special care about single valued tuple.compulsary the value
should ends with comma, otherwise it is not treated as tuple.
1) t=(10)
2) print(t)
3) print(type(t))
4)
5) Output
6) 10
7) <class 'int'>
Eg:
1) t=(10,)
2) print(t)
3) print(type(t))
4)
5) Output
6) (10,)
7) <class 'tuple'>
Q) Which of the following are valid Tuples?
1) t = ()
2) t = 10, 20, 30, 40
3) t = 10
4) t = 10,
5) t = (10)
6) t = (10,)
7) t = (10, 20, 30, 40)
Tuple Creation:
1) t = ()
Creation of Empty Tuple
2) t = (10,)
t = 10,
Creation of Single valued Tuple, Parenthesis are Optional, should ends with Comma
3) t = 10, 20, 30
t = (10, 20, 30)
Creation of multi values Tuples & Parenthesis are Optional.
1) By using Index:
1) t = (10, 20, 30, 40, 50, 60)
2) print(t[0]) 10
3) print(t[-1]) 60
,
2) By using Slice Operator:
1) t=(10,20,30,40,50,60)
2) print(t[2:5])
3) print(t[2:100])
4) print(t[::2])
Output
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
Tuple vs Immutability:
Once we creates tuple, we cannot change its content.
Hence tuple objects are immutable.
Eg:
t = (10, 20, 30, 40)
t[1] = 70 TypeError: 'tuple' object does not support item assignment
Eg: t = (10,20,30,40)
print(len(t)) 4
2) count()
To return number of occurrences of given element in the tuple
3) index()
Returns index of first occurrence of the given element.
If the specified element is not available then we will get ValueError.
4) sorted()
To sort elements based on default natural sorting order
1) t=(40,10,30,20)
2) t1=sorted(t)
3) print(t1)
4) print(t)
Output
[10, 20, 30, 40]
(40, 10, 30, 20)
1) t = (40,10,30,20)
2) print(min(t)) 10
3) print(max(t)) 40
6) cmp():
֍ It compares the elements of both tuples.
֍ If both tuples are equal then returns 0
֍ If the first tuple is less than second tuple then it returns -1
֍ If the first tuple is greater than second tuple then it returns +1
1) t1=(10,20,30)
2) t2=(40,50,60)
3) t3=(10,20,30)
4) print(cmp(t1,t2)) -1
5) print(cmp(t1,t3)) 0
6) print(cmp(t2,t3)) +1
Eg:
a = 10
b = 20
c = 30
d = 40
t = a, b, c, d
print(t) (10, 20, 30, 40)
Here a, b, c, d are packed into a Tuple t. This is nothing but Tuple packing.
Tuple unpacking is the reverse process of Tuple packing.
We can unpack a Tuple and assign its values to different variables.
1) t=(10,20,30,40)
2) a,b,c,d=t
3) print("a=",a,"b=",b,"c=",c,"d=",d)
Output: a= 10 b= 20 c= 30 d= 40
Note: At the time of tuple unpacking the number of variables and number of values
should be same, otherwise we will get ValueError.
Eg:
t = (10,20,30,40)
a, b, c = t ValueError: too many values to unpack (expected 3)
Tuple Comprehension:
Tuple Comprehension is not supported by Python.
t = ( x**2 for x in range(1,6))
Here we are not getting tuple object and we are getting generator object.
D:\Python_classes>py test.py
<class 'generator'>
1
4
9
16
25
D:\Python_classes>py test.py
Enter Tuple of Numbers:(10,20,30,40)
The Sum= 100
The Average= 25.0
D:\Python_classes>py test.py
Enter Tuple of Numbers: (100,200,300)
The Sum= 600
The Average= 200.0
List Tuple
1) List is a Group of Comma separeated 1) Tuple is a Group of Comma separeated
Values within Square Brackets and Values within Parenthesis and
Square Brackets are mandatory. Parenthesis are optional.
Eg: i = [10, 20, 30, 40] Eg: t = (10, 20, 30, 40)
t = 10, 20, 30, 40
2) List Objects are Mutable i.e. once we 2) Tuple Objeccts are Immutable i.e. once
creates List Object we can perform any we creates Tuple Object we cannot
changes in that Object. change its content.
Eg: i[1] = 70 t[1] = 70 ValueError: tuple object
does not support item assignment.
3) If the Content is not fixed and keep on 3) If the content is fixed and never changes
changing then we should go for List. then we should go for Tuple.
4) List Objects can not used as Keys for 4) Tuple Objects can be used as Keys for
Dictionries because Keys should be Dictionries because Keys should be
Hashable and Immutable. Hashable and Immutable.