0% found this document useful (0 votes)
43 views15 pages

List and Tuples

The document provides an overview of list manipulation in Python, detailing the characteristics of lists, including mutability and slicing, as well as various built-in functions for list operations. It also includes multiple-choice questions, short answer questions, and explanations about tuples, highlighting their differences from lists. Additionally, it discusses nested lists and the significance of lists in Python programming.

Uploaded by

adi.chauhan.483
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)
43 views15 pages

List and Tuples

The document provides an overview of list manipulation in Python, detailing the characteristics of lists, including mutability and slicing, as well as various built-in functions for list operations. It also includes multiple-choice questions, short answer questions, and explanations about tuples, highlighting their differences from lists. Additionally, it discusses nested lists and the significance of lists in Python programming.

Uploaded by

adi.chauhan.483
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/ 15

Class XI (Comp Sc)

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

Very Short Answer Type Questions


Q1. What do you understand by mutability?
Ans: Mutable means changeable. In Python, mutabletypes are those whose values can be changed
inplace.Onlythreetypesaremutablein python–Lists,Dictionariesand Sets.
Q2. Startwiththelist[8,9,10].Dothefollowingusinglistfunctions:
(a) Setthesecondentry(index1)to17
(b) Add4,5and6tothe endofthelist.
(c) Removethefirstentryfromthelist.
(d) Sortthelist
(e) Doublethelist.
(f) Insert 25 at index 3

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.

Q2. What are nested Lists?


Ans: A list can have an element in it,which itself is a list.Such a list is called nested list.e.g.
L=[1,2,3,4,[5,6,7],8]
Q3.Discuss the utility and significance of Lists.
Ans: The list is a most versatile datatype available in Python which can be written as a list of
comma-separated values(items) between square brackets. Important thing about a list is that items in a
list need not be of the same type. List is majorly used with dictionaries when there is large number of data.
Q4. What is the purpose of the del operator and pop method? Try deleting a slice.
Ans: del operator is used to remove an individual item,or to remove all items identified by a slice.
It is to be used as per syntax given below–
>>>del List[index]
>>>del List[start:stop]
Pop method is used to remove single element, not list slices.The pop() method removes an
individual

item and returns it.I ts syntax is–


>>>a=List.pop() #thiswill remove last item and deleted item will be assigned to a.
>>>a=List[10] #thiswill remove the item at index10 and deleted item will be assigned to a.
Q5. What are list slices?
Ans: List slices,like string slices are the sub part of a list extracted out. Indexes can be used to create list
slices as per following format:
seq=L[start:stop]
Q6. What do you understand by true copy of a list? How is it different from shallow copy?
Ans:A shallow copy means constructing a new collection object and then populating it with references to the
child objects found in the original. In essence, a shallow copy is only one leveldeep. The copying process does
not recurse and therefore won‘t create copies of the child objects themselves.
True Copy means you can create a copy of a list using New_list=My_list. The assignment just copies the
reference to the list, not the actual list, so both new_list and my_list refer to thesamelistaftertheassignment.
Q7. Predict the output – Ans:

Q8. Predict the output – Ans:

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.

Q2.WAP to Calculate mean of the given list of numbers.


Ans.numbers = [23, 45, 12, 67, 9, 31]
# Calculate the sum of the numbers
total = 0
for num in numbers:
total += num
# Calculate the mean
mean = total / len(numbers)
print(“The mean of the numbers is :”,mean)
Q3. WAP to search for an element in a given list of numbers.
Ans.lst=eval(input(“Enter list:”))
length=len(lst)
element=int(input(“Enter element to be searched for:”))
for i in range(0,length):
if element==lst[i]:
print(element,”found at index”,i)
break
else:
print(element,”not found in given 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))

Q5. Differentiate between append( ) and extend( ) functions.


Ans. The append() function/method adds a single item to the end of the existing list. It doesn’t return a
new list. Rather, it modifies the original list. The extend() adds all multiple items in the form of a list at the
end of another list.

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

Accessing Elements of a tuple (Indexing)

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’)

>>> str[2] = ‘M’


>>> str[-3] = ‘T’

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:

str = (‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’)


for x in str:
print(str[x])
The above loop will produce result as :
C
O
M
P
U
T
E
R
Tuple Operations
Concatenation (Joining Tuples)
The + operator is used to join (Concatenate) two tuples
Exp.
>>> T1 = (10,20,30)
>>> T2 = (11,22,33)
>>> T1 + T2
+ Operator concatenates Tuple T1 and Tuple T2 and creates a new Tuple
(10, 20, 30, 11, 22, 33)
Repetition
* Operator is used to replicate a tuple specified number of times, e.g.
>>> T = (10, 20, 30)
>>> T * 2
(10, 20, 30, 10, 20, 30)
Membership:
The ‘in’ operator checks the presence of element in tuple. If the element present it returns True, else it
returns False.
For Exp. str = (‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’)
‘M’ in str => Returns True
‘S’ in str => Returns False

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'

The min( ) function


This method returns element having minimum value, i.e.,
>>> T = (10,20,30,40,50,600,70,80,90)
>>>min(T)
10

>>> T = ('pankaj','pinki','parul')
>>> min(T)
'pankaj'

The sum( ) function


This method is used to find the sum of elements of the tuple, i.e.,
>>> T = (10,20,30,40,50,600,70,80,90)
>>> sum(T)
990

The index( ) method


It returns the index of an existing element of a tuple., i.e.,
>>> T = (10,20,30,40,50,600,70,80,90)
>>> T.index(50)
4
But if the given item does not exist in tuple, it raises ValueError exception.
>>> T = (10,20,30,40,50,600,70,80,90)
>>> T.index(55)
ValueError: tuple.index(x): x not in tuple

The count( ) method


This method returns the count of a member / element (Number of occurrences) in a given tuple.,
i.e.,
>>> T = (10,20,30,20,20,0,70,30,20)
>>> T.count(20)
4

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

>>> str = "Computer" # String


>>> T = tuple(str) # Creates a tuple from the string
>>> print(T)
('C', 'o', 'm', 'p', 'u', 't', 'e', 'r')

The sorted( ) method


This function takes the name of the tuple as an argument and returns a new sorted list with sorted
elements in it.
>>> T = (10,40,30,78,65,98,23)
>>> X = sorted(T) # Make a list of values arranged in ascending order
>>> print(X)
[10, 23, 30, 40, 65, 78, 98]

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

Tuple Assignment (Unpacking Tuple)

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

# Program to find sum of all the elements of a tuple


T = (10, 2, 30, 4, 8, 5, 45)
print(T)
s = sum(T)
print("Sum of elements : ", s)

Output
(10, 2, 30, 4, 8, 5, 45)
Sum of elements : 104

# Program to find minimum and maximum values in a tuple


T = (10,2,30,4,8,5,45)
print(T)
minimum = min(T)
maximum = max(T)
print("Minimum Value : ", minimum)
print("Minimum Value : ", maximum)

Output
(10, 2, 30, 4, 8, 5, 45)
Minimum Value : 2
Minimum Value : 45

# Program to find mean of values stored in a tuple


T = (10,2,30,4,8,5,46)
print("Tuple :", T)
s = sum(T)
NumberOfElements = len(T)
average = s/NumberOf Elements
print("Mean of elements : ", average)

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)

Q) Write a program to find sum of even and odd elements of tuple


T = (10,23,30,65,70)
sumE = 0
sumO = 0
for x in T:
if (x%2 == 0):
sumE = sumE + x
else:
sumO = sumO + x
print(T)
print("sum of Even numbers :",sumE)
print("Sum of Odd Numbers : ", sumO)
MCQs
Consider a tuple in python named Months = (‘Jul’, ‘Aug’, ‘Sep’). Identify the C
1. invalid statement(s) from the given below statements:-
a) S = Months[0] b) print(Months[2])
c) Months[1] = ‘Oct’ d) LIST1 =list(Months)
Suppose tuple1 = (2, 33, 222, 14, 25), What is tuple1[ ::-1]? D
2. a) [2, 33, 222, 14] b) Error
c) 25 d) [25, 14, 222, 33, 2]
Consider the following declaration of Record, what will be the data type of Record? B
3. Record=(1342, “Pooja” , 45000, “Sales”)
a) List b) Tuple c) String d) Dictionary
Which operator is used for replication? C
4. a) + b) % c) * d) //
What will be the output of following Python Code? Tp = (5) D
5. Tp1 = tp * 2
Print(len(tp1))
a) 0 b) 2 c) 1 d) Error

Q1. Define Tuple?


Ans. A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list or
even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by
commas.
For example T = (1,2, ‘a’, 5) # T is a tuple

Q2) Write a statement to create an empty tuple named T1?


Ans: T1 = ( ) or T1 = tuple( )

Q3) Write the code to convert given list L into a tuple?


Ans: T = tuple(L)

Q4) What is the difference between a List and a Tuple?


Ans:
List Tuple
Elements are enclosed in square Elements are enclosed in
brackets i.e. [ ] parenthesis i.e. ( )
It is mutable data type It is immutable data type
Iterating through a list is slower as Iterating through a tuple is faster
compared to tuple as compared to list

Q5) What is unpacking Tuple?


Ans: 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.
Q7) Write a program to create a tuple and find sum of its alternate elements? Ans:T =
(10,23,30,65,70)
sum = 0
for a in T[0:5:2]: sum = sum + a
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)

You might also like