4.8.Python_List
4.8.Python_List
LIST
Introduction:
List Creation:
List Manipulation
Iterating Through A List
Slicing of A List
Updating Lists
Add Item to A List
Add Two Lists
Delete Item From A List
Built in functions related with LIST in Python
The len() function
The sort() method
The min() method
The max() method
The list() method
The append() method
The clear() method
The reverse() method
The sum() function
The range() function
The pop() function
The remove() function
The index() function
The insert() function
LIST
Introduction:
In Python, a list is a kind of container that contains collection of any kind of values. A List is a
mutable data type which means any value from the list can be changed. For changed values
, Python does not create a new list. List is a sequence like a string and a tuple except that list
is mutable whereas string and tuple are immutable. In this chapter we will see the
manipulation on lists. We will see creation of list and various operation on lists via built in
functions.
List Creation:
List is a standard data type of Python. It is a sequence which can store values of any kind.
Lists are enclosed in square brackets [ ] and each item is separated by a comma.
For example - [ ] Empty list [1, 2, 3] integers list [1, 2.5, 5.6, 9] numbers list (integer and
float) [ ‘a’, ‘b’, ‘c’] characters list [‘a’, 1, ‘b’, 3.5, ‘zero’] mixed values list [‘one’, ’two’, ’three’]
string list
In Python, only list and dictionary are mutable data types, rest of all the data types are
immutable data types.
List is a collections of items and each item has its own index value. Index of first item is 0
and the last item is n-1.Here n is number of items in a list.
List can be created as: list1 = [‘English’, ‘Hindi’, 1997, 2000]; list2 = [11, 22, 33, 44, 55 ];
list3 = [“a”, “b”, “c”, “d”];
List Manipulation
Access Items From A List List items can be accessed using its index position. e.g. list =[3,5,9]
print(list[0]) will give output as : 3 print(list[1]) will give output as : 5 print(list[2]) will give
output as : 9 print(‘Negative indexing’) will give output as : Negative indexing print(list[-1])
will give output as : 9 print(list[-2]) will give output as : 5 print(list[-3]) will give output as : 3
List elements can be accessed using looping statement. e.g. list =[3,5,9] for i in range(0,
len(list)): print(list[i])
Output :
359
Slicing of A List
Output
[‘I’, ‘N’, ‘D’] [‘I’, ‘A’] [‘I’, ‘N’, ‘D’, ‘I’, ‘A’]
Updating Lists
We can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator. e.g.
list = [‘English’, ‘Hindi’, 1997, 2000] print ("Value available at index 2 : ", list[2]) list[2:3] =
2001,2002 #list[2]=2001 for single item update print ("New value available at index 2 : ",
list[2]) print ("New value available at index 3 : ", list[3])
Output
(’Value available at index 2 : ’, 1997) (’New value available at index 2 : ’, 2001) (’New value
available at index 3 : ’, 2002)
append() method is used to add an Item to a List. e.g. list=[1,2] print(‘list before append’,
list) list.append(3) print(‘list after append’, list)
Output
(‘list before append’, [1, 2]) (‘list after append’, [1, 2, 3])
NOTE :- extend() method can be used to add multiple item at a time in list. eg -
list.extend([3,4])
OUTPUT
[1,2,3,4]
e.g. list=[1,2,3] print(‘list before delete’, list) del list [1] print(‘list after delete’, list)
Output
Using len() function, we can find the length of a list i.e. the number of elements present in
the list. Example
Output
Using the sort() method, we can sort any list but the elements in the list should be of the
same datatypes like int or string. Example
Output
[10, 12, 13, 34, 45, 50] [‘A’, ‘B’, ‘a’, ‘b’, ‘c’, ‘d’]
Using the min() method, we can find the minimum value from the list but the elements in the
list should be of the same datatypes like int or string. Example
Output
10 A
Using the max() method, we can find the maximum value from the list but the elements in
the list should be of the same datatypes like int or string. Example
Output
50 d
Using the list() method, we can convert any sequence datatype into lists. Datatypes like
Tuples, Strings, Sets, etc can be converted to Python Lists. Example
myTuple = (1, 2, 3, 4)
myList1 = list(myTuple)
myString = "Hello"
myList2 = list(myString)
mySet = {1, 2, 3, 4}
myList3 = list(mySet)
print(myList1)
print(myList2)
print(myList3)
Output
[1, 2, 3, 4] [‘H’, ‘e’, ‘l’, ‘l’, ‘o’] [1, 2, 3, 4]
Using the append() method, we can add an element at the end of a Python List. Example
myList = [1, 2, 3, 4]
myList.append(5)
print(myList)
Output
[1, 2, 3, 4, 5]
Using the clear() method, we can clear all elements from a Python List i.e. we can delete all
elements. Example
myList = [1, 2, 3, 4]
myList.clear()
print(myList)
Output
[]
Using the copy() method, we can copy one Python list to another Python list. Example
myList1 = [1, 2, 3, 4]
myList2 = myList1.copy()
print(myList2)
Output
[1, 2, 3, 4]
Note:- You can not copy a list just by using the “=” operator as it will be called as assigning
one list to another not copying. If you do that, then any changes you will make in the first list
will also apply to the second list. Example
myList1 = [1, 2, 3, 4]
myList2 = myList1 # referring one list to another
print(myList1)
print(myList2)
myList1.append(5) # appending 5 in myList1
print(myList1)
print(myList2) # changes will appear in myList2 too
Output
Using the reverse() method, we can reverse the order of the position of elements in a Python
List. Example
myList = [1, 2, 3, 4]
myList.reverse()
print(myList)
Output
[4, 3, 2, 1]
myList = [1, 2, 3, 4, 5, 6, 7]
addition1 = sum(myList)
print(addition1)
addition2 = sum(myList, 3)
print(addition2)
Output
28 31
Using the range() function, we can get a list that contains a sequence of numbers, starting
from 0 by default, and increments by 1 (by default), and stops before the specified number,
since using the range() function we can create a list of the desired sequence which will save
our time and work. Example
myList1 = [range(15)]
myList2 = [range(4, 15)]
myList3 = [range(4, 15, 3)]
print(myList1)
print(myList2)
print(myList3)
Output
Surprised, yes this is not we wanted, actually, we need to unpack the result of the range()
function using the argument-unpacking operator i.e. *. Example
myList1 = [*range(15)] myList2 = [*range(4, 15)] myList3 = [*range(4, 15, 3)] print(myList1)
print(myList2) print(myList3)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [4, 7, 10, 13]
Using the pop() function, we can remove the last value of the list. If we want to remove any
other value from the list using the pop() function, then we need to pass the index number to
the pop() function, else the last value will be removed. The pop() function always returns the
removed value. Example
Output
Using the remove() function, we can remove any element from the list. To remove an
element, pass the element as an argument to the function. The remove() function does not
return any value and gives an error if the value is not present in the list. Example
Output
None [5, 6, 7, 8, 9, 10, 11] [5, 6, 8, 9, 10, 11] [5, 6, 8, 9, 10] Traceback (most recent call last):
File “main.py”, line 8, in print(myList.remove(3)) # 3 not present ValueError: list.remove(x): x
not in list
What if one value is repeated? In that case, the remove() function removes the first one only
and leaves other values at the same place where they were before. Example
Output
Now, let’s see one-liner to remove all the similar elements from the list. Example
Output
Using the index() function, we can find/search for an element in any list. As soon as the
element is found, it returns the index of the element. If there are two or more elements with
similar values in the list, it will return the index of the element with the lowest index number.
We can pass two more arguments to the index() function, start(from where we want to start
searching the element in the list), and end(where we want to end search the element in the
list). These two arguments are optional. Syntax:
myList = [4, 5, 6, 7, 4, 8, 9]
print(myList.index(5))
print(myList.index(4))
print(myList.index(4, 2, 5))
print(myList.index(4, 2, 3))
Output
1 0 4 Traceback (most recent call last): File “main.py”, line 5, in print(myList.index(4, 2, 3))
ValueError: 4 is not in list
Using the insert() function, we can insert an element in the list on our desired location/index.
Syntax:
listname.insert(index, element)
If the index value is greater than or equal to the len(listname), then the element is inserted
at the end of the list. It does not return any value and gives an error if it is used with other
objects instead of the list. Example
myList = [4, 5, 6, 7, 4, 8, 9]
myList.insert(0, 1)
print(myList)
myList.insert(1, 2)
print(myList)
myList.insert(10, 12)
print(myList)
Output
[1, 4, 5, 6, 7, 4, 8, 9]
[1, 2, 4, 5, 6, 7, 4, 8, 9]
[1, 2, 4, 5, 6, 7, 4, 8, 9, 12]