0% found this document useful (0 votes)
33 views10 pages

List and tuple datatype in Python (1)

Uploaded by

saiyansh mahajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views10 pages

List and tuple datatype in Python (1)

Uploaded by

saiyansh mahajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

List and Tuple datatype in Python

Ques : What is a List?


A list is a sequence of comma separated values (elements) enclosed in square brackets []. The
values in a list may be of different types (integer, float, string etc.). Lists are mutable i.e. values
in a list can be changed. A list is also dynamic i.e., we can add and delete elements from the list
at any time.
Examples:
L1 = [ ' En gl i sh ', 4 5, ' Mat h s ' , 86 , 'R aj es h ', 1 234 ]
L2 = [ ' A V Ram an ' , 35 , ' T G T C ompu t er ' , 456 70 .00]
L3 = [ ] # E mpt y l i st
L4 = [ 12 , 15 , ' Man i sh ', [4 5, 8 7], 2 3] # N e st ed Li st
L5 = [ ' s on i a ' , ( ' E00 1 ' , ' D00 1 ') , 34 000] # Tu pl e wi th i n a Li s t

Ques : How are the indexes allotted in a List in Python? How can we access individual
characters in a List in Python?
Python indexes the list element from left to right and from right end to left. From left to right,
the first element of a list has the index 0 and from right end to left, the extreme right index
element of a list is –1. Individual elements in a list can be accessed by specifying the list name
followed by a number in square brackets ([]).

Index from left 0 1 2 3 4 5

List Elements English 65 Maths 97 Science 89

Index from right end -6 -5 -4 -3 -2 -1

L1 = [ ' En gl i sh ' ,65 , ' Math s ', 97 , 'S ci en c e ' ,89]


pri n t ( L1 ) # p ri n t s al l el em en t s [' En gl i sh ', 65 , 'M at h s ', 97, 'S ci en c e ', 89 ]
pri n t ( L1 [4]) # p ri n t s 5 t h el em en t ' Sci en c e '
pri n t ( L1 [- 3] ) # p ri n t s 3 r d l ast el e men t 97

Ques : What do you mean by Lists are mutable?


Lists are mutable, which means we can change their elements. Using the bracket operator ([ ])
on the left side of an assignment, we can update one of the elements. For example:
f ri en d s = [' An m ol ' , ' K i ran ' , ' Vi mal ', 'Si dh ar th ' , ' Ri ya ']
f ri en d s[0] = 'J ati n ' # 0 t h el e m en t ch an ged t o Ja ti n
f ri en d s[ - 1 ] = 'Vi d ya ' # l a st el e m en t c h an ged t o Vi dy a
pri n t ( f ri en d s) # [ 'J ati n ', 'K i ran ' , ' Vi mal ', ' Si dh ar th ' , ' Vi dya ']

Ques : What is List Concatenation ? Give Example.


Concatenation means joining two List operands by linking them end-to-end. In list
concatenation, + operator concatenate two lists with each other and produce a third list.
Example :
L1 = [ 10 , 20 ,3 0 ]
L2 = [' a' ,22 ,3 3]
L1 + = L2
pri n t( L1) # [1 0, 2 0, 30 , ' a ', 2 2, 33]

Ques : How can you replicate a List? Give example.


List can be replicated any number of times with the asterisk "*" operator.
L1 = [ 'W el c o m e' ]
pri n t( L1 * 2) # [ ' W el c om e ', 'W el c om e ']
L2 = [1 , 2 .0 , 'a ']
pri n t( L2 * 3) # [ 1, 2 .0 , ' a' , 1 , 2. 0, ' a' , 1 , 2. 0, 'a ']
L3 = [0] * 10
pri n t( L3) # [ 0, 0 , 0 , 0 , 0 , 0, 0, 0 , 0, 0]
pri n t ( L1 * - 2) # []
Page 1 of 10
List and Tuple datatype in Python
Ques : How do you slice a List in Python?
A subList of a List is called a slice. Subsets of Lists can be taken using the slice operator with
[start : stop : step] in square brackets separated by a colon. It extracts the part of the List from
the start position and up to but not including stop position, i.e. (stop –1). If step is negative slicing
is done backwards.
Index from left 0 1 2 3 4 5
List Elements English 65 Maths 97 Science 89
Index from right end -6 -5 -4 -3 -2 -1
L1 = ['English', 65 , 'Maths' , 97, 'Science', 89 ]
Slicing Result Explanation
print (L1[2:5]) ['Maths', 97, 'Science'] Prints 2nd to 4th element
print (L1[1:-2] [65, 'Maths', 97] Prints 1st to -3rd element
print (L1[ :4]) ['English', 65, 'Maths', 97] Prints 0th to 3rd element
print (L1[2: ]) ['Maths', 97, 'Science', 89] Prints 2nd to last element
print (L1 [ : ]) ['English', 65, 'Maths', 97, 'Science', 89] Prints 0th to last element
print (L1 [ 1: 5 :2]) [65, 97] Prints every 2nd character from 1st to 5th
character
print (L1 [ : : 2 ]) ['English', 'Maths', 'Science'] Prints every 2nd character from 0th to
last character
print (L1 [ : :-2]) [89, 97, 65] Prints every 2nd character from last to
beginning character
print(L1[2]) Science Prints 3rd element

Ques : Explain how do you use slice operator to replace list elements?
Assignment operator (=) is used to replace the elements specified with slice operator. For
example:
L1 = ['English', 65 , 'Maths' , 97, 'Science', 89 ]
L1[1] = 90 ['English', 90, 'Maths', 97, 'Science', 89] Replaces the element at index 1 to 90
print(L1) Prints the entire List
L1[2:4] = [‘IP’,99] ['English', 90, 'IP', 99, 'Science', 89] Replaces elements from index 2 to 3
print(L1) Prints the entire List
L1[1:3] = [ ] ['English', 99, 'Science', 89] Replaces elements from 1 to 2 with [ ]
print(L1) Prints the entire List

Ques : Explain the use of Membership operators.


The membership operators are used to test whether a value is found in a sequence. There are
two types of membership operators.
Operator Description
This operator tests if an element is present in list or not. If an element exists in the list,
in it returns True, otherwise False. For example,
Li st1 = [1 , 15 , 10 , 5, - 99 , 10 0]
pri n t(10 i n Li st1) # T ru e
pri n t( - 5 0 i n Li st1) # Fal s e
Mo n th s = ['J an ', 'F e b' , ' Ma r ', 'Ap r ', 'M ay ', 'Ju n ']
pri n t ( ' D ec ' i n M on t h s) # Fal s e
`
not in The not in operator evaluates True if it does not find a variable in the specified sequence,
otherwise False. For example,
Li st1 = [1 , 15 , 10 , 5, - 99 , 10 0]
pri n t(10 n ot i n Li s t1 ) # Fal s e
pri n t( - 1 00 n ot i n Li s t1) # T ru e
Mo n th s = ['J an ', 'F e b' , ' Ma r ', 'Ap r ', 'M ay ', 'Ju n ']
pri n t( 'D e c' n ot i n M on th s ) # T ru e
Page 2 of 10
List and Tuple datatype in Python
Ques : Explain the use of Identity operators.
Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below –
Operator Description

is Is operator evaluate to True if the variables on either side of the operator point to the
same object (i.e having same ids) and False otherwise.
L1 = [1 , 15 , 10 , 5, - 99, 1 00]
L2 = L1
pri n t( L1) # [1 , 15 , 10 , 5, - 99, 1 00]
pri n t( L2) # [1 , 15 , 10 , 5, - 99, 1 00]
pri n t(i d(L1 )) # 57 902 504
pri n t(i d(L2 )) # 57 902 504
pr i nt (L 1 i s L 2 ) # T ru e
L2[ 0] =1 0
pri n t( L1) # [ 10 , 1 5, 1 0, 5 , - 99, 1 00]
pri n t( L2) # [ 10 , 1 5, 1 0, 5 , - 99, 1 00]

is not Is not operator evaluate to True if the variables on either side of the operator point to
the different objects and False otherwise.
L1 = [1 , 15 , 10 , 5, - 99, 1 00]
L2 = [1 , 15 , 10 , 5, - 99, 1 00]
pri n t(i d(L1 )) # 6 524 257 6
pri n t(i d(L2 )) # 1 772 250 4
pr i nt (L 1 i s not L2 ) # T ru e

Ques: Give the output of all print statement lines:


Al i st = [' a' , ' b' , ' c ' , 'd ', ' e' , ' f ']
Al i st[1:3] = [ 'x ' , ' y' ]
pri n t ( Al i st) ____ ___ ____ ___ __ ____ ___ _
Al i st = [' a' , ' b' , ' c ' , 'd ', ' e' , ' f ']
Al i st[1:3] = []
pri n t ( Al i st) ____ ___ ____ ___ __ ____ ___ _
Al i st = [' a' , ' d' , ' f ']
Al i st[1:1] = [ 'b' , ' c ' ]
pri n t ( Al i st) ____ ___ ____ __ _ __ ____ ___ _
Al i st[4:4] = [ 'e ']
pri n t ( Al i st) ____ ___ ____ ___ __ ____ ___

Ques: How is a List different from a string?


Strings List
String is a sequence of characters enclosed in List is a sequence of items of different
quotes datatypes enclosed in [] brackets
Strings are immutable i.e. its characters Lists are mutable i.e. its elements can be
cannot be changed. changed.
Insertion and removal from in between is not Lists are dynamic i.e. we can insert or
possible in Strings but they can be appended remove elements from within Lists.
to other Strings and vice versa

Page 3 of 10
List and Tuple datatype in Python
Ques: Explain the use of del statement in Python for removing a list element
The del statement is used to delete elements from a list. del statement deletes the element but
does not return the removed item. For example:
Name = ['Anmol', 'Kiran', 'Vimal', 'Sidharth', 'Riya', 'Vimal']
del Name[0] # deletes the first element, i.e. 'Anmol'
print (Name) # returns: ['Kiran', 'Vimal', 'Sidharth', 'Riya', 'Vimal']
Num = [23, 54, 34, 44, 35, 66, 27, 88, 69, 54]
del Num[4] # deletes the 5th element, i.e., 35
print (Num) # returns: [23, 54, 34, 44, 66, 27, 88, 69, 54]
L1 = [‘Eng’, 99,’Sc’,89]
del L1[3] # Removes the element at index 3
print(L1) # ['Eng', 99,’Sc.’]
del [ 2: ] # Removes all elements from index 2 onwards
print(L1) # ['Eng', 90]
del L1 # Removes the entire list

Ques : What is a Nested List? Give Example


Nested List is a List within a List For Example:

0 1 2

0 1 2 0 1
red yellow blue Pink cyan teal
-3 -2 -1 -2 -1

-3 -2 -1

colours = [ ['red', 'yellow', 'blue' ] , 'pink', [ 'cyan', 'teal'] ]


colours[0] # refers to ['red', 'yellow', 'blue']
colours[0][0] # 'red'
colours[0][2] # 'blue'
colours[1] # 'pink'
colours[1][0] # 'p'
colours[2][1] # 'teal'
colours[2][1][0] # 't'

L1 = [ 1, [73,89,42,32], 62, [24,32], 99 ]


L1[1][0] # refers to 73
L1[1][0][0] # error – digits cannot be separated from a number

Ques : Explain the usage of Built-in List functions in Python


Consider the following lists
L1 = [ 10, 20, 30, 50, 40]
L2 = [ ‘india’,’china’,’bangladesh’]
Function Result Description
print (len(L1)) 5 Returns number of elements in the list.
print (len(L2)) 3
print (max(L1)) 50 Returns item with maximum value.
print (max(L2)) india
print (min(L1)) 10 Returns item with minimum value.
print (min(L2)) bangladesh
print (sum(L1)) 150 Returns sum of all the elements.
print (sum(L2)) Error
Page 4 of 10
List and Tuple datatype in Python
Ques : Write a Python script to display max, min, sum and mean of 5 numbers

Ques : Explain the usage of List Methods in Python


Consider the following lists
L1 = [ 10, 20, 30, 50, 40]
L2 = [ ‘india’,’china’,’bangladesh’]
Method Description
List.append(obj) Adds obj to the end of the list
L1.append(10)
print(L1) # [10, 20, 30, 50, 40, 10]
L2.append('indonesia ')
print(L1) # ['india', 'china', 'bangladesh', 'indonesia']
List.count(obj) Returns how many times obj occurs in the list.
print(L1.count(10)) #2
print(L2.count("USA ")) #0
List.extend(seq) Extends the contents of sequence to the list
L3 = [ 11 , 22 , 33 ]
L1.extend(L3)
print(L1) #[10, 20, 30, 50, 40, 10, 11, 22, 33]
List.index(obj) Returns the index of first occurrence of obj
print(L1.index(10)) #0
List.insert(index,obj) Inserts the object obj at index position
L1.insert(0,5)
print(L1) #[5, 10, 20, 30, 50, 40, 10, 11, 22, 33]
List.pop(index) Removes and returns the last object if no index is provided
print(L1.pop()) #33
print(L1.pop(len(L1)-1)) # 22
print(L1) #[5, 10, 20, 30, 50, 40, 10, 11]
List.remove(obj) Removes the first occurrence of obj
L1.remove(10)
print(L1) #[5, 20, 30, 50, 40, 10, 11]
list.reverse( ) Reverses objects of a list.
L1.reverse()
print(L1) # [ 11, 10, 40, 50, 30, 20, 5]
list.sort( ) sorts the objects of list in ascending order.
If reverse=True, sorts in descending order.
L1.sort()
print(L1) #[5, 10, 11, 20, 30, 40, 50]
vowels = [ ‘a’ ,’u’ ,’e’ ‘i’ ,’ o’ ]
vowels.sort();
print(vowels) #['a', 'e', 'i', 'o', 'u']
vowels.sort(reverse=True);
print(vowels) #['u', 'o', 'i', 'e', 'a']

Page 5 of 10
List and Tuple datatype in Python
Ques: Consider the following lists and predict the output of the following?
L1 = [‘Siddhant’, 12, ‘Monica’, 34 ]
L2 = [ ‘Sarika’, 54 ]

print (L1 + L2)


L2 += L1
print( L2)
print (L2 * 2)
print (54 in L2)

print (‘Monica’ not in L1)

Ques: Write a single statement to replace: 12,’Monica’, 34 in List L1 with 21,’Rishu’,43.

____________________________________________________________________________

Ques: Write a single statement to create a list L3 containing 5 zeros using Repetition
operator (*).
____________________________________________________________________

Ques: Write a single statement to remove L1 , L2 and L3


____________________________________________________________________

Ques: If L1 = [‘English’, 65, ‘Mathematics’, 87, ‘Science’, 89 ]


a). Write the index of L1 from left to right and right to left.
___________________________________________________________________

b). What will be the output of the following?


print(L1[3])

print(L1[2:5])

print(L1[2:22])

print(L1[1:-2])
print(L1[ :4])
print(L1[2: ])
print( L1 [:] )
L1[1] = 90
print (L1)
del L1[3]
print (L1)

Ques:To print the 4th value in the list L1, Of the following statements, which one are
correct? Justify.
print ( L1[3] )
print ( L1[2+1] )
print ( L1[3.0] )

___________________________________________________________________

Page 6 of 10
List and Tuple datatype in Python
Ques:Write the statement to replace ‘Mathematics’, 87, ‘Science’ with empty List [ ]

___________________________________________________________________.

Ques: Consider the list


L = [12, 15, [16, ‘Bhumika’ ], 85]
What will be the output of the following?
a) print (L[2]) ______________________
b) print (L[2][0]) _______________________
c) print(L[2][1]) _______________________

Ques: Consider the list


L1 = [4, 17, 10, 19, 15, 20]
L2 = [23, 43, 11, 15, 19]
What will be the output of the following?
L1.append(10)
print(L1)
print(len(L1))
print( len(L2)
L1.count(10)
L1.extend(L2)
print(L1)
print(L1.index(15))
L1.insert(2, 30)
print(L1)
L1.pop()
print (L1)
L2.pop( len(L2) – 1 )
print (L2)
L1.remove(23)
print (L1)
L1.reverse()
print (L1)
L1.sort()
print (L1)
L1.sort(reverse = True)
print(L1)

Ques: How can you get a List of Sub Strings from a given String?
split() method returns a list of sub strings after breaking the given string by the specified
separator.
str.split (separator, maxsplit)
separator : The string splits at the specified separator. If is not provided then any white space
(space, newline, tab) is a separator.
maxsplit : It is the maximum number of splits to be done. If it is not provided then there is no
limit.
For Example:

Page 7 of 10
List and Tuple datatype in Python
breakfast = 'Menu- Bread Butter Buiscuit Banana'
print (breakfast.split()) ['Menu-', 'Bread', 'Butter', 'Buiscuit', 'Banana']
print (breakfast.split(' ',4)) ['Menu-', 'Bread', 'Butter', 'Buiscuit', 'Banana']
print (breakfast.split(' ',3)) ['Menu-', 'Bread', 'Butter', 'Buiscuit Banana']
print (breakfast.split(' ',2)) ['Menu-', 'Bread', 'Butter Buiscuit Banana' ]
print (breakfast.split(' ',1)) ['Menu-', 'Bread Butter Buiscuit Banana' ]
print (breakfast.split(' ',0)) ['Menu- Bread Butter Buiscuit Banana' ]

print (breakfast.split('B')) ['Menu- ', 'read ', 'utter ', 'uiscuit ', 'anana']
print (breakfast.split('B',4)) ['Menu- ', 'read ', 'utter ', 'uiscuit ', 'anana']
print (breakfast.split('B',3)) ['Menu- ', 'read ', 'utter ', 'uiscuit Banana']
print (breakfast.split('B',2)) ['Menu- ', 'read ', 'utter Buiscuit Banana' ]
print (breakfast.split('B',1)) ['Menu- ', 'read Butter Buiscuit Banana' ]
print (breakfast.split('B',0)) ['Menu- Bread Butter Buiscuit Banana' ]

Ques: What will be the output of the following?

sentence = "Hello there!, all good?"


print(sentence.split())

msg = 'Python\n is fun'


print(msg.split('\n'))

color = "red:green:blue"
a,b,c = col or.spli t(':')
print(a,c)

grocery = 'cheese,eggs,tea,coffee'
grocery.split(',')
grocery.split(',',1)
grocery.split(',',2)
grocery.split(',',3)

txt = "hello, my name is Peter, I am 26


years old"
x = txt.split(", ")
print(x)

txt = "apple#banana#cherry#orange"
x = txt.split("#",2)
print(x)

words = “This is random text we’re


going to split apart”
words2 = words.split(“ “)
print(words2)

Page 8 of 10
List and Tuple datatype in Python
Ques: What is a tuple in Python?
A tuple is a sequence of comma separated values (items) enclosed in round brackets. Items in
the tuple may have different data types.
For Example:
T1 = (‘Aman’, 12, 4500, ‘Jatin’, 34, 8793) # A tuple with integers and strings
T2 = (12, ‘Monica’, 89.8, ‘Shilpa’, (45, 67), 78.5) # A Nested tuple
T3 = (‘E001’, [‘D01’, T05’], 23, 12) # A tuple having a list
T4 = ( ) # An empty tuple with no contents
T5 = ( 23, ) # Tuple with a single value has a comma at the end

Ques: What is the difference between a tuple and a list in Python?


Tuple List
Tuple is immutable i.e., its contents List is mutable i.e., its contents can be
cannot be changed or removed. changed or removed.
The elements in tuple are within The elements in List are within square
parentheses. brackets.
Example, T1 = (‘Manish’, 12, 345) Example, L1 = [‘Manish’, 12, 345]
Tuple can be converted into a List by List can be converted into a Tuple by
using the function : using the function :
L1=list(T1) T1=tuple(L1)
print(L1) print (T1)

Ques: Explain the basic Tuple Operations in Python?


Operation Expression Results
Concatenation a = (2, 4, 6)
b = (5, 7, 9)
c=a+b
print ( c, b, a, sep="~~") (2, 4, 6, 5, 7, 9)~~(5, 7, 9)~~(2, 4, 6)
Repetition t = ("welcome",)
print ( t * 2 ) ('welcome', 'welcome')
Membership nos = ( 1, 3, 5,7 )
print(4 in nos) False
print(3 in nos) True
print(2 not in nos) True
Identity L1 = (1, 15, 10, 5, -99, 100)
L2 = L1
print(id(L1)) 37939328
print(id(L2)) 37939328
print (L1 is L2) True
L3 = (1, 15, 10, 5, -99, 100)
print(id(L3)) 37939328
print (L1 is L3) True

Ques: Explain Tuple Slicing


Like string indices, tuple indices also start at 0, and can be sliced. For Example:
0 1 2 3
0 1
T1 = ( 'monica',12,'seema', (13,17 ) ) ‘monica’ 12 ‘seema’ 13 17
-2 -1
-4 -3 -2 -1

Page 9 of 10
List and Tuple datatype in Python
Slicing operation Result Explanation
print(T1[1] ) 12 Prints the second item in the tuple
print(T1[1:4]) (12, 'seema', (13, 17)) Prints elements from index 1 to 3
print(T1[1:-2]) (12,) Prints element from 1, stops before -2
print(T1[ : 3]) ('monica', 12, 'seema') Prints elements from index 0 to index 2
print(T1[2: ] ) ('seema', (13, 17)) Prints elements from index 2 till the end
print (T1 [ 1: 4 :2]) (12, (13, 17)) Prints every 2nd character from 1st to 3rd character
print (T1 [ : : 2 ]) ('monica', 'seema') Prints every 2nd character from 0th to last character
print (T1 [ : :-2]) ((13, 17), 12) Prints every 2nd character from last to beginning character
T1[2] = 'garima' Error Because tuple is immutable, values cannot be changed

Ques: Explain the Built-in Tuple Functions

Function Description Example Result


a = ( 10,20,30,40)
len(t1) Returns number of elements in tuple len(a) 4
t1
max(t1) Returns the element with maximum max(a) 40
value in t1
min(t1) Returns the element with minimum min(a) 10
value in t1
sum(t1) Returns the sum of all the elements sum(a) 100
in the tuple t1
list(t1) Converts the tuple t1 to a list data list(a) [10,20,30,40]
type

Ques : Explain Tuple element replacement


Individual items of a tuple cannot be changed once assigned. But, if the element is itself a
mutable data type, like a list, its nested items can be changed.

0 1 2 3

0 1
10 20 30 40 50
-2 -1

-4 -3 -2 -1

a = (10,20,[30,40],50)
a[0] =100 # error, because tuple value cannot be changed
a[2][0] =60 # list value changed
print(a) # (10, 20, [60, 40], 50)

Ques: Explain the use of del statement in Python for removing tuple elements

del a[0] # error, because individual tuple value cannot be deleted


del a[2][1] # since a[2][1] is nested list , its values can be changed or deleted
print(a) (10, 20, [60], 50)
del T1 # Removes entire tuple T1

Page 10 of 10

You might also like