List and Tuples
List and Tuples
LIST MANIPULATION
List: A list is a collection of comma-separated values (items) of same or different type within square ( )
brackets. List is a mutable data type.
Slicing: Slicing is an operation in which we can slice a particular range from a sequence.
List slices are the sub parts extracted from a list.
Nested List: When a list appears as elements of another list, it is called a nested list.
Built-in Function (Manipulating Lists)
Function Syntax Description
list() list(sequence) It returns a list created from the passed
arguments, which should be a sequence
type(string, list, tuple etc.). if no argument is
passed, it will create an empty list.
append() list.append (items) It adds a single item to the end of the list.
extend() list1.extend (list2) It adds one list at the end of another list.
insert() list.insert (index_no, value) It adds an element at a specified index
reverse() list.reverse () It reverses the order of the elements in a list.
index() list.index (item) It returns the index of first matched item from
the list.
len() len (list) Returns the length of the list i.e. number of
elements in a list
sort() list.sort () This function sorts the items of the list.
clear() list.clear () It removes all the elements from the list.
count() list.count (element) It counts how many times an element has
occurred in a list and returns it.
sorted() sorted(sequence,reverse=False) It returns a newly created sorted list; it does not
change the passed sequence.
pop() list.pop (index) It removes the element from the specified index
and also returns the element which was
removed.
remove() list.remove (value) It is used when we know the element to be
deleted, not the index of the element.
max() max(list) Returns the element with the maximum value
from the list.
min() min(list) Returns the element with the minimum value
from the list
sum() sum(list) It returns sum of elements of the list.
MCQs
1 1. The data type list is an ordered sequence which is and made
up of one or more elements.
a. Mutable
b. Immutable
c. Both a) and b)
d. None of the above
2 Which statement from the list below will be create a new list?
a. new_l = [1, 2, 3, 4]
b. new_l = list()
c. Both a) and b)
d. None of the above
3 What will be the output of the following python code
new_list = [‘P’,’y’,’t’,’h’,’o’,’n’]
print(len(new_list))
a. 6 b. 7c. 8d. 9
4 Python allows us to replicate a list using repetition operator depicted by
symbol .
a. – b. + c. / d. *
5 We can access each element of the list or traverse a list using a .
a. for loop b. while loop
c. Both a) and b) d. None of the above
6 a single element passed as an argument at the end of the list.
a. append() b. extend()
c. insert() d. None of the above
7 returns index of the first occurrence of the element in the list. If
the element is not present, ValueError is generated.
a. insert() b. index()
c. count() d. None of the above
8 function returns the element whose index is passed as parameter
to this function and also removes it from the list.
a. push() b. remove()
c. pop() d. None of the above
9 What will be the output of the following python code.
new_list = “1234”
print(list(new_list))
a. [‘1’, ‘2’, ‘3’, ‘4’] b. (‘1’, ‘2’, ‘3’, ‘4’)
c. {‘1’, ‘2’, ‘3’, ‘4’} d. None of the above
10 Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], which of the following is correct syntax
for slicing operation?
a) print(list1[0]) b) print(list1[:2])
c) print(list1[:-2]) d) all of the mentioned
11 Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?
a) Error b) None c) 25 d) 2
12 Suppose list1 is [1, 3, 2], What is list1 * 2 ?
a) [2, 6, 4] b) [1, 3, 2, 1, 3]
c) [1, 3, 2, 1, 3, 2] d) [1, 3, 2, 3, 2, 1].
13 What is the output when following code is executed ?
>>>list1 = [11, 2, 23]
>>>list2 = [11, 2, 2]
>>>list1 < list2 is
a) True b) False c) Error d) None
14 To insert 5 to the third position in list1, we use which command ?
a) list1.insert(3, 5) b) list1.insert(2, 5)
c) list1.add(3, 5) d) list1.append(3, 5)
In the following questions(15 to 20) , a statement of assertion (A) is
followed by a statement of reason(R) . Make the correct choice as :
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False (or partially True)
(d) A is false( or partially True) but R is True
15 Assertion: In python, unlike other types, you can change elements of a list in
place.
Reason: Lists are mutable sequences.
16 Assertion: Any comma-separated group of values creates a list.
Reason: Only a group of comma-separated values or expressions enclosed in [ ]
, creates a list.
17 Assertion: Lists and strings have similar types of indexing.
Reason: Both lists and strings have two-way indexing , forward indexing and
backward indexing.
18 Assertion :Lists are similar to strings in a number of ways like indexing , slicing
and accessing individual elements.
Reason : Lists, unlike strings , are mutable.
19 Assertion : The membership operators in and not in work in the same way on
lists as they do , with strings.
Reason :Some operators work differently on strings and lists , such as + and * .
20 Assertion: A list slice is an extracted part of a list.
Reason: A list slice is a list in itself.
1 a 11 c
2 c 12 c
3 a 13 b
4 d 14 b
5 c 15 a
6 c 16 d
7 b 17 a
8 c 18 b
9 a 19 c
10 d 20 b
Answers:
(a) list[1]=17
(b) list.append(4)
list.append(5)
list.append(6)
(c) list.pop(0)
(d) list.sort()
(e) list=list*2
(f) list.insert(3,25)
Q3. Ifais[1,2,3],what is the difference(ifany) between a*3 and [a,a,a]?
Ans: a*3 will produce [1,2,3,1,2,3,1,2,3],means a list of integers and [a,a,a] will produce[[1,2,3],[1,2,3],
[1,2,3]], means list of lists
Q4. If a is [1,2,3],is a*3 equivalent to a+ a+a?
Ans: Yes, Both a*3and a+a+a will produce same result.
Q5. If ai s[1,2,3],what is the meaning of a[1:1]=9?
Ans: This will generate an error―Type Error: can only assign an iterable.
Q6. If a is[1,2, 3],what is the meaning of a[1:2]=4 and a[1:1]=4?
JjAns: These will generate an error―Type Error:can only assign an iterable .
Q7. What are list slices?
Ans: List slices are the sub-part of a list extracted out. You can use indexes of the list elements to create list
slices as per following format. Syntax is as follows:- Seq=ListName [start:stop]
Q8.Does a slice operatoral ways produce a newlist?
Ans: Yes, this will create a new list.
ShortAnswerTypeQuestions
Q1. How are lists different from strings when both are sequences?
Ans: Lists are similar to strings in many ways like indexing, slicing, and accessing individual elements but
they are different in the sense that Lists are mutable while strings are immutable.
Inconsecutive locations, strings store the individual characters while list stores the references of its elements.
Strings store single type of elements-all characters while lists can store elements belonging to different types.
UNSOLVED QUESTIONS
Q1. WAP to find minimum element from a list of elements along with its index in the list.
Q2.WAP to Calculate mean of the given list of numbers.
Q3. WAP to search for an element in a given list of numbers.
Q4. WAP to count the frequency of a given element in the list of numbers.
Q5. Differentiate between append( ) and extend ( ) functions in Python.
UNSOLVED QUESTIONS(ANSWERS)
Q1. WAP to find minimum element from a list of elements along with its index in the list.
Q4. WAP to count the frequency of a given element in the list of numbers.
Ans . L=[2,58,95,999,65,32,15,1,7,45]
n=int(input("Enter the number : "))
print("The frequency of number ",n," is ",L.count(n))
TUPLES
A tuple is a collection which is ordered and immutable (We cannot change elements of a tuple in place).
Tuples are written with round brackets. Tuples are used to store multiple items in a single variable. Tuples
may have items with same value.
Exp. T = () # Empty Tuple
T = (1, 2, 3) # Tuple of integers
T = (1,3.4,7) # Tuple of numbers
T = (‘a’, ‘b’, ‘c’) # Tuple of characters
T = (‘A’,4.5,’Ram’,45) # Tuple of mixed values
T = (‘Amit’, ‘Ram’, ‘Shyam’) # Tuple of strings
Creating Tuples
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas.
Exp. T = (10,20, ‘Computer’,30.5)
If there is only a single element in a tuple then the element should be followed by a comma, otherwise it will
be treated as integer instead of tuple. For example
T = (10) # Here (10) is treated as integer value, not a tuple
T1 = (10,) # It will create a tuple
Difference between List and Tuple
List Tuple
Elements are enclosed in square brackets i.e. [ ] Elements are enclosed in parenthesis i.e. ( )
It is mutable data type It is immutable data type
Iterating through a list is slower as compared to tuple Iterating through a tuple is faster as compared
to list
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing, for example
If str = (‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’)
Traversing a Tuple
Traversing a tuple means accessing and processing each element of it. The for loop makes it easy to
traverse or loop over the items in a tuple. For example:
The not in operator returns True if the element is not present in the tuple, else it returns False.
‘M’ not in str => Returns False
‘S’ not in str => Returns True
Slicing
It is used to extract one or more elements from the tuple. Slicing can be used with tuples as it is used in
Strings and List. Following format is used for slicing:
S1 = T[start : stop : step]
The above statement will create a tuple slice namely S1 having elements of Tuple T on indexes start,
start+step, start+step+step, …, stop-1.
By default value of start is 0, value of stop is length of the tuple and step is 1
For Example:
>>> T = (10,20,30,40,50,60,70,80,90)
>>> T[2:7:3]
(30, 60)
>>> T[2:5]
(30, 40, 50)
>>> T[::3]
(10, 40, 70)
T[5::]
(60, 70, 80, 90)
Built-in functions/methods:
The len( ) function
This method returns length of the tuple or the number of elements in the tuple, i.e.,
>>> T = (10,20,30,40,50,60,70,80,90)
>>> len(T)
9
The max( ) function
This method returns element having maximum value, i.e.,
>>> T = (10,20,30,40,50,600,70,80,90)
>>>max(T)
600
>>> T = ('pankaj','pinki','parul')
>>> max(T)
'pinki'
>>> T = ('pankaj','pinki','parul')
>>> min(T)
'pankaj'
>>> T = (10,20,30,20,20,0,70,30,20)
>>> T.count(30)
2
The tuple( ) method
This function creates an empty tuple or creates a tuple if a sequence is passed as argument.
>>> L = [10, 20, 30] # List
>>> T = tuple(L) # Creates a tuple from the list
>>> print(T)
(10, 20, 30)
>>> Y = sorted(T, reverse = False) # Make a list of values arranged in ascending order
>>> print(Y)
[10, 23, 30, 40, 65, 78, 98]
>>> Z = sorted(T, reverse = True) # Make a list of values arranged in descending order
>>> print(Z)
[98, 78, 65, 40, 30, 23, 10]
It allows a tuple of variables on the left side of the assignment operator to be assigned respective
values from a tuple on the right side. The number of variables on the left should be same as the number of
elements in the tuple.
Exp.
>>> T = ('A', 100, 20.5)
>>> x,y,z = T
>>> print(x,y,z)
A 100 20.5
Nested Tuple
A tuple containing another tuple in it as a member is called a nested tuple, e.g., the tuple shown below
is a nested tuple:
>>> students = (101,'Punit', (82,67,75,89,90)) # nested tuple
>>> len(students)
3
>>> print(students[1]) # 2nd element of tuple
Punit
>>> print(students[2]) # 3rd element of tuple
(82, 67, 75, 89, 90)
>>> print(students[2][3]) # Accessing 4th element of inner tuple
89
Output
(10, 2, 30, 4, 8, 5, 45)
Sum of elements : 104
Output
(10, 2, 30, 4, 8, 5, 45)
Minimum Value : 2
Minimum Value : 45
Output
Tuple : (10, 2, 30, 4, 8, 5, 46)
Mean of elements : 15.0
# Write a program to find the given value in a tuple
T = (10,2,34,65,23,45,87,54)
print("Tuple :", T)
x = int(input("Enter value to search:"))
for a in T:
if a == x :
print("Value found")
break
else:
print("Value not found")
Output
Tuple : (10, 2, 34, 65, 23, 45, 87, 54)
Enter value to search:45
Value found
Q) Write a program to find sum of elements of tuple without using sum() function?
T = (10,20,30)
sum = 0
for x in T:
sum = sum + x
print(T)
print(sum)
Q8) Write a program to count vowels in a tuple? Ans: T = tuple(input("Enter Name :"))
print(T) v = 0
for ch in T:
if ch in ['a','e','i','o','u']: v = v + 1
print("No. of vowels : ",v)