0% found this document useful (0 votes)
9 views

List, Tuple Data Types - Python

Uploaded by

adityapratap.cse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

List, Tuple Data Types - Python

Uploaded by

adityapratap.cse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

LIST

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.

Creation of List Objects:


1) We can create empty list object as follows...

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]

3) With Dynamic Input:

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

5) With split() Function:

1) s="Learning Python is very very easy !!!"


2) l=s.split()
3) print(l)
4) print(type(l))

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

Accessing Elements of List:


We can access elements of the list either by using index or by using slice operator(:)

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

2) By using Slice Operator:


Syntax: list2 = list1[start:stop:step]

Start  It indicates the Index where slice has to Start


Default Value is 0

Stop  It indicates the Index where slice has to End-1


Default Value is max allowed Index of List ie Length of the List

Step  increment value


Default Value is 1

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]

Traversing the Elements of List:


The sequential access of each element in the list is called traversal.

1) By using while Loop:


1) n = [0,1,2,3,4,5,6,7,8,9,10]
2) i = 0
3) while I < len(n):
4) print(n[i])
5) i=i+1

D:\Python_classes>py test.py
0
1
2
3
4
5
6
7
8
9
10

2) By using for Loop:


1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for n1 in n:
3) print(n1)
D:\Python_classes>py test.py
0
1
2
3
4
5
6
7
8
9
10

3) To display only Even Numbers:


1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for n1 in n:
3) if n1%2==0:
4) print(n1)

D:\Python_classes>py test.py
0
2
4
6
8
10

4) To display Elements by Index wise:


1) l = ["A","B","C"]
2) x = len(l)
3) for i in range(x):
4) print(l[i],"is available at positive index: ",i,"and at negative index: ",i-x)

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.

Differences between append() and insert()


append() insert()
In List when we add any element it will In List we can insert any element in
come in last i.e. it will be last element. particular index number

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)

ValueError: list.remove(x): x not in list

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]

If the list is empty then pop() function raises IndexError

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.

n.pop(index)  To remove and return element present at specified index.


n.pop()  To remove and return last element of the list

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.

append(), insert(), extend()  for increasing the size/growable nature


remove(), pop()  for decreasing the size /shrinking nature

III) Ordering Elements of List:

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.

 For numbers  Default Natural sorting Order is Ascending Order


 For Strings  Default Natural sorting order is Alphabetical Order

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)

TypeError: '<' not supported between instances of 'str' and 'int'

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

But in Python 3 it is invalid.

To Sort in Reverse of Default Natural Sorting Order:


We can sort according to reverse of default natural sorting order by using reverse=True
argument.

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]

Aliasing and Cloning of List Objects:


The process of giving another reference variable to the existing list is called aliasing.

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]

To overcome this problem we should go for cloning.


The process of creating exactly duplicate independent object is called cloning.

We can implement cloning by using slice operator or by using copy() function.

1) By using Slice Operator:


1) x = [10,20,30,40]
2) y = x[:]
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
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

Q) Difference between = Operator and copy() Function


֍ = Operator meant for aliasing
֍ copy() Function meant for cloning
Using Mathematical Operators for List Objects:
We can use + and * operators for List objects.

1) Concatenation Operator (+):


We can use + to concatenate 2 lists into a single list

1) a = [10, 20, 30]


2) b = [40, 50, 60]
3) c = a+b
4) print(c)  [10, 20, 30, 40, 50, 60]

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

2) Repetition Operator (*):


We can use repetition operator * to repeat elements of list specified number of times.

1) x = [10, 20, 30]


2) y = x*3
3) print(y)  [10, 20, 30, 10, 20, 30, 10, 20, 30]

Comparing List Objects


We can use comparison operators for List objects.

1) x = ["Dog", "Cat", "Rat"]


2) y = ["Dog", "Cat", "Rat"]
3) z = ["DOG", "CAT", "RAT"]
4) print(x == y)  True
5) print(x == z)  False
6) print(x != z)  True

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:

1) x = ["Dog", "Cat", "Rat"]


2) y=["Rat", "Cat", "Dog"]
3) print(x>y)  False
4) print(x>=y)  False
5) print(x<y)  True
6) print(x<=y)  True

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.

Nested List as Matrix:


In Python we can represent matrix by using nested lists.

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

Elements by Row wise:


[10, 20, 30]
[40, 50, 60]
[70, 80, 90]

Elements by Matrix style:


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.

Syntax: list = [expression for item in list if condition]

1) s = [ x*x for x in range(1,11)]


2) print(s)
3) v = [2**x for x in range(1,6)]
4) print(v)
5) m = [x for x in s if x%2==0]
6) print(m)

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)

Output: ['B', 'N', 'V', 'C']

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]

Q) Write a Program to display Unique Vowels present in the


given Word?
1) vowels=['a','e','i','o','u']
2) word=input("Enter the word to search for vowels: ")
3) found=[]
4) for letter in word:
5) if letter in vowels:
6) if letter not in found:
7) found.append(letter)
8) print(found)
9) print("The number of different vowels present in",word,"is",len(found))

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.

4) By using tuple() Function:


1) list=[10,20,30]
2) t=tuple(list)
3) print(t)
4)
5) t=tuple(range(10,20,2))
6) print(t)

Accessing Elements of Tuple:


We can access either by index or by slice operator

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

Mathematical Operators for Tuple:


We can apply + and * operators for tuple

1) Concatenation Operator (+):


1) t1=(10,20,30)
2) t2=(40,50,60)
3) t3=t1+t2
4) print(t3)  (10,20,30,40,50,60)

2) Multiplication Operator OR Repetition Operator (*)


1) t1=(10,20,30)
2) t2=t1*3
3) print(t2)  (10,20,30,10,20,30,10,20,30)
Important Functions of Tuple:
1) len()
To return number of elements present in the tuple.

Eg: t = (10,20,30,40)
print(len(t))  4

2) count()
To return number of occurrences of given element in the tuple

Eg: t = (10, 20, 10, 10, 20)


print(t.count(10))  3

3) index()
 Returns index of first occurrence of the given element.
 If the specified element is not available then we will get ValueError.

Eg: t = (10, 20, 10, 10, 20)


print(t.index(10))  0
print(t.index(30))  ValueError: tuple.index(x): x not in tuple

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)

We can sort according to reverse of default natural sorting order as follows


t1 = sorted(t, reverse = True)
print(t1)  [40, 30, 20, 10]
5) min() And max() Functions:
These functions return min and max values according to default natural sorting order.

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

Note: cmp() function is available only in Python2 but not in Python 3

Tuple Packing and Unpacking:


We can create a tuple by packing a group of variables.

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.

1) t= ( x**2 for x in range(1,6))


2) print(type(t))
3) for x in t:
4) print(x)

D:\Python_classes>py test.py
<class 'generator'>
1
4
9
16
25

Q) Write a Program to take a Tuple of Numbers from the Keyboard


and Print its Sum and Average?
1) t=eval(input("Enter Tuple of Numbers:"))
2) l=len(t)
3) sum=0
4) for x in t:
5) sum=sum+x
6) print("The Sum=",sum)
7) print("The Average=",sum/l)

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

Differences between List and Tuple:


 List and Tuple are exactly same except small difference: List objects are mutable where
as Tuple objects are immutable.
 In both cases insertion order is preserved, duplicate objects are allowed, heterogenous
objects are allowed, index and slicing are supported.

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.

You might also like