CH. 11 AND 12 LIST AND TUPLE MANIPULATION
CH. 11 AND 12 LIST AND TUPLE MANIPULATION
11 LIST MANIPULATION
What is a list in Python?
Ans. A list in Python is a compound data type because it can store
any data type in it.
ListVariable = [List of Values]
L1 = [10,25,3,99,105]
L2 = *“Ram”, “Raheem”, “Deepa”, “Ashok”+
L3 = *1, “Ram”, 2, “Raheem”, 3, “Deepa”+
L4 = *1, “Ram”, 85.25, 2, “Raheem”, 75.5+
L5 = *25, 36, 60.251, 33, 0.25, “Python”+
What is an empty list?
Ans. A list without any element is called empty list.
L=[]
An empty list can also be created as follows:
L = list( )
What is a nested list?
Ans. A list within a list is called as nested list.
>>> L = [1, 2, 3, [10, 20, 30], 4, 5]
>>> L
[1, 2, 3, [10, 20, 30], 4, 5]
>>> L[0]
1
>>> L[0:3] >>> L[3][0]
[1, 2, 3] 10
>>> L[0:5] >>> L[3][0:3]
[1, 2, 3, [10, 20, 30], 4] [10, 20, 30]
>>> L[7]
IndexError: list index out of range
Creating a list using keyboard with list( ) function:
L = list(input("Enter List Element: "))
print("The List is: ",L)
Enter List Element: PYTHON
The List is: ['P', 'Y', 'T', 'H', 'O', 'N']
Enter List Element: 15,75
The List is: ['1', '5', ',', '7', '5']
The list( ) function always creates a string type of list even though if
we enter digits. To enter a list of integers, float, string or compound
data types the following method is used:
L = eval(input("Enter list: "))
print("The list is: ",L)
Enter list: [25,5.5,"Python",100]
The list is: [25, 5.5, 'Python', 100]
The eval( ) Function: This function can be used to evaluate and
return the result of an expression given as a string. E.g.
Result=eval('5*7')
print(Result) # Output will be 35
# a = [10, 11, [20, 21], 12] # a = [10, 11, [20, 21], 12]
#b=a # b = list(a)
# print(a) # print(a)
# print(b) # print(b)
# a[0] = 3 * 10 # a[0] = 3 * 10
# a[2][0] = 3 * 10 # a[2][0] = 3 * 10
# print(a) # print(a)
# print(b) # print(b)
# b[0] = 5 * 5 # b[0] = 5 * 5
# b[2][0] = 5 * 5 # b[2][0] = 5 * 5
# print(a) # print(a)
# print(b) # print(b)
Creating a Copy of List: True Copy and Partial True Copy
Example of Tuples:
T1 = ( ) # Empty Tuple
T2 = (1, 2, 3) # Tuple with integers
T3 = (15.25, 36. 45, 105. 105) # Tuple with float numbers
T4 = (15, 35, 45.002, 187, -125.2501) # Tuple with integers and floats
T5 = (“Jai”, “Riya”, “Khushi”) # Tuple with strings
T6 = ([1, 2, 3], [10, 20, 30], [100, 200, 300]) # Tuple with lists
T7 = (1, “A”, “Amit”, 45.5) # Tuple with mixed data types
T8 = ((1, 3, 5), (2, 4, 6), (1, 2, 3, 4, 5, 6)) # Nested tuple
Ways of creating Tuples:
Using Direct Assignment:
T = (1, 2, 3)
Using tuple( ) function:
T = tuple(iterable) # iterable means list, string, dictionary, set, tuple
e.g. T = tuple([1, 2, 3])
a = tuple(eval(input(“Enter elements of tuple:")))
print(a)
a, b, c, *d, e = [1,2,3,4,5,6]
print(a)
print(b) Execute the following functions on tuple.
print(c) len()
print(d) max()
print(e) min()
index()
count()