Listrr
Listrr
INTRODUCTION
Lists are used to store multiple items in a single variable.
Lists are enclosed in square brackets and the elements of the list are separated by
commas.
List is a mutable data type, means that the contents of the list can be changed after it
is created.
There is another way (Backward indexing) for indexing from last element (index = -1) to
first element (index = -length of the list).
LIST OPERATIONS
Concatenation (+ Operator): Python allows us to join two or more lists using + operator.
ex: - >>> l1 = [1,3,5,7,9]
>>> l2 = [2,4,6,8,10]
>>> l3 = [‘abc’, “qwe”]
>>>l1 + l2 + l3 # + operator
[1,3,5,7,9,2,4,6,8,10, ‘abc’, “qwe”]
Repetition/ Replication Operator (* operator): Python allows us to replicate a list using
repetition operator depicted by symbol ‘*’.
ex: - >>> str1 = ['Help']
>>> str1 * 4
[' Help ', ' Help ', ' Help’, ' Help']
Like strings, the membership operators IN NOT IN operator returns True if the element is
checks, if the element is present in the list then not present in the list, else it
returns True, returns False.
else returns False. ex: - >>>‘N’ not in [‘A’, ‘P’, ‘S’ ]
ex: - >>>‘N’ in [‘A’, ‘P’, ‘S’ ] True
False >>>‘A’ not in [‘A’, ‘P’, ‘S’ ]
>>>‘S’ in [‘A’, ‘P’, ‘S’ ] False
True
List Slicing: - Like strings, the slicing operation can also be applied to lists. List elements
can be accessed in subparts.
Syntax- list_name[start:stop:step]
L = [2,7,9,10,13,15,17,19,23,25] Slice Generates
L[4: ] [13, 15, 17, 19, 23, 25]
L[ : 3] [2,7,9]
L[2: 5] [9,10, 13]
L[4: : 2] [13, 17, 23]
L[2 : 7 : 2] [9, 13, 17]
L[ : : -1] [25, 23, 19, 17, 15, 13, 10, 9, 7, 2]
L[ : : -2] [25, 19, 15, 10, 7]
L[6 : 1: -2] [17, 13, 9]
L[-8 : 8 ] [9, 10, 13, 15, 17, 19]
L[3 : -2 : 2] [10, 15, 19]
L[6 : -9 : -2] [17, 13, 9]
Traversing: - Traversing means iterating through the elements of a list, one element at a
time.
ex: - >>>L1 = [1,2,3,4] output- 1
>>>for a in L1: 2
print(a) 3
4
List Comparisons: - The relational operators >, >=, <, <=, ==, != can be applied for
comparison between two lists results will come in True or False. The following rules are
observed:
(a) For equality (==) operator: - Equality evaluates to True only when all the elements of
one list match all the elements of the other list and both the list have the same number of
elements.
(b) For all other operators - The elements are compared sequentially using the operator
under consideration.
(c) If two lists are of different lengths and if one of the list has an element at an index
position and the other list does not have an element at that position then the evaluation
proceeds as follows:
List Functions
1. len() function
This function returns the length of a list .
len(<list>)
L1 = [13,18,11,16,18,14]
len(L1) will return 6
2. list () function
This function converts the passed argument to a list. The passed argument could be a string, a list or
even a tuple.
list(<argument>)
example s = “Computer”# list(s) # [‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
tpl=1,2,3,4,5,6 # list(tpl) #(1,2,3,4,5,6]
The extend() method is also used for adding multiple elements (given in the form of a list) to a list.
List.extend(<list>)
That is extend() takes a list as an argument and appends all of the elements of the argument list to
the list object on which extend() is applied.
t1=[‘a’,’b’,’c’]
t2=[‘d’,’e’]
t1.extend(t2)
print(t1) # [‘a’,’b’,’c’,’d’,’e’]
print(t2) # [‘d’,’e’]
5. The insert () function
If you want to insert an element somewhere in between or any position of your choice for such a
requirement insert() is used.
List.insert(<pos>,<item>)
The first argument <pos> is the index of the element before which the second argument <item> to
be added.
t1=[‘a’,’e’,’u’]
t1.insert(2,’i')
print(t1)
[‘a,’e’,’i',’u’]
list.insert(0,x) will insert element x at the front of the list i.e. at index 0.
list.insert(len(list),x) will insert element x at the end of the list i.e. index equal to length of the list
6. The count() function
This function returns the count of the item that you passed as argument. If the given item is not in
the list, it returns zero.
List.count(<item>)
For instance:
L1 = [13,18,20,10,18,23]
print(L1.count(18))
2
print(L1.count(28))
0
7. The Index() function
This function returns the index of first matched item from the list.
List.index(<item>)
L1 = [13,18,11,16,18,14]
print(L1.index(18))
1
However, if the given item is not in the list, it raises exception ValueError.
8. The remove() function
The remove() method removes the first occurrence of given item from the list. It is used as per
following format:
List.remove(<value>)
The remove() will report an error if there is no such item in the list. Consider the example:
t1=[‘a’,’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘a’)
print(t1)
[’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘p’)
print(t1)
[’e’,’i',’q’,’a’,’q’,’p’]
print(t1.remove(‘k’))
ValueError
The pop() is used to remove the item from the list. It is used as per the following syntax:
List.pop(<index>)
Thus, pop() removes an element from the given position in the list, and return it. If no index is
specified, pop() removes and returns the last item in the list.
t1 = [‘k’,’a’,’i',’p’,’q’,’u’]
ele = t1.pop(0)
print(ele)
‘k’
The reverse() reverses the item of the list. This is done “in place” i.e. id does not create a new list.
The syntax to use reverse method is:
List.reverse()
For example:
t1 = [‘e’,’i',’q’,’a’,’q’,’p’]
t1.reverse()
print(t1)
[‘p’,’q’,’a’,’q’,’i',’e’]
The sort() function sorts the items of the list, by default in increasing order. This is done “in place”
i.e. it does not create a new list. It is used as per following syntax:
List.sort()
For example:
t1 = [‘e’,’i',’q’,’a’,’q’,’p’]
t1.sort()
print(t1)
[‘a’,’e’,’i',’p’,’q’,’q’]
List.sort(reverse=True)
min(<list>)
For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then
This function returns the maximum value present in the list. This function will work only if all
elements of the list are numbers or strings. This function gives the maximum value from a given list.
Strings are compared using its ordinal values/Unicode values. This function is used as per following
format:
max(<list>)
For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then
This function returns the total of values present in the list. This function will work only if all elements
of the list are numbers. This function gives the total of all values from a given list. This function is
used as per following format:
sum(<list>)
This method removes all the items from the list and the list becomes empty list after this function.
This function returns nothing. It is used as per following format:
List.clear()
For instance:
L1=[2,3,4,5]
L1.clear()
print(L1)
[]
Assignment- LIST
Q1. Write a program to print list having numbers less than 20.
Q.2 What will be the output of the following program?
l=[6,12,18,24,30]
for i in l:
for j in range(1,i%4):
print(j,'#',end='')
print( )
Q.3 Write a program that reverses a list of integers.
Q.4 Write a program to find the number of times an element occurs in the list.
Q.5 Write a program to find the largest and smallest number in a list.
Q.6 Write a program to check if a number is present in the list or not. If the number is
present, print the position of the number. Print an appropriate message if the number
is not present in the list.
TUPLE
A tuple is a collection which is ordered and immutable.
Elements of a tuple are enclosed in parenthesis and are separated by commas.
Tuples can store a sequence of values belonging to any type.
Ex:- T1 = ( ) # Empty Tuple
T2 = (4,5,6) # Tuple of integers
T3 = (1.5,4,9) # Tuple of numbers
T4 = (‘x’, ‘y’, ‘z’) # Tuple of characters
T5 = (‘a’,1.5,’APS’,45) # Tuple of mixed values
T6 = (‘KVS’, ‘LBS’, ‘APSSP’) # Tuple of strings
>>>t2 = (10,) # Single element tuple
Note:- comma is necessary in single value tuples. Without a comma it will be a value, not a
tuple.
>>>t3=(10,20,30,40,50) # Long tuple
>>>t4=(6,(4,5),9,7) # Nested Tuple
●tuple( ) function is used to create a tuple from other sequences.
●Indexing of tuple is similar to indexing of list.
●Difference between List and Tuple
TRAVERSING A TUPLE
Ex:-
T1=(2,4,6,8,10) Output:
for a in T1:
print(a)
Unpacking Tuples
Creating a tuple from a set of values is called packing.
Creating individual values from a tuple’s element is called unpacking.
For example
t = (1, 2, ‘A’, ‘B’) # Packing
Tuple functions
For example:
emp = (‘John’, 10000, 24, ‘Sales’)
print(len(emp))
4
This method returns the element from the tuple having maximum value.
Example:
tp1 = (10,12,14,20,22,24,30,32,34,-2)
print(max(tp1))
34
tp2 = (“Karan”, “Zubin”, “Zara”, “Ana”)
print(max(tp2))
Zubin
Note that max() applied on sequences like tuples/lists etc. will return a maximum value
ONLY IF the sequence contains values of same type.
Example:
tp1 = (10,12,14,20,22,24,30,32,34,-2)
print(min(tp1))
-2
tp2 =(“Karan”, “Zubin”, “Zara”, “Ana”)
print(min(tp2))
Ana
The index() works with tuples in the same way it works with lists.
Example:
t1 =(3,4,5,6.0)
print(t1.index(5))
2
Example:
t1=(2,4,2,5,7,4,8,9,9,11,7,2)
print(t1.count(2))
3
t1.count(7)
2
For an element not in tuple, it returns 0.
This method is actually constructor method that can be used to create tuples from
different types of values.
Example:
a. Creating empty tuple
>>>tuple()
()
t1 =(3,4,5,6,0)
print(sorted(t1))
[0, 3, 4, 5, 6]
print(sorted(t1, reverse = True))
[6, 5, 4, 3, 0]
Indirectly Modifying Tuples
Tuple is Immutable:
Tuple is an immutable data type. It means that the elements of a tuple cannot be
changed after it has been created.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
Tuple operations:
Concatenation:-
Python allows us to join tuples using concatenation operator depicted by symbol +.
Q. Write a program to create a tuple and find sum of its alternate elements?
Q Write a program to input n numbers from the user. Store these numbers in a tuple. Print the
maximum and minimum number from this tuple.