A list can be defined as a collection of values or items of different Data types.
In more simpler terms, List is a collection of items enclosed between Square brackets []. Unlike other data types like Integer , Float and boolean, List stores multiple values in a single variable. For Example:
In [1]:
varlist = [1,2,3,4,5,6,7,8,9]print(varlist)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Memory Allocation of List items:
As we know that Lists are a sequence of items, hence Each item of list gets store in different memory block, something like this:
In [ ]:
varlist = ["console","flare","python","data"]
You Must have realized that there are a lot of similarity in a string and list. We will cover that in detail in this session.
Indexing of Lists:
As we know that items of lists are stored in different memory blocks, each item within a list is given an index number.
Python offers two different indexing :
Positive Index Numbers : Positive index numbers starts from zero (0) and left to right.
Negative Index Numbers: Negative index numbers starts from -1 and from right to left.
Empty list is a list with no items in it. We can create an empty list by using [].
In [28]:
empty_list = []
print(empty_list)
[]
Properties of a list:
1.Lists are Ordered:
When You define a list , its items are stored and assigned to specific index number. It means list items are ordered . To Explain it better, Here is an Example:
No matter , How many times you print list , items are assigned to their particular index number and won't change their place unless we do it deliberately.In [ ]:
To understand it even more better, Let's take two list with same data items and compare it.
Here items in varlist and anotherlist is same but both lists are in different order. Lists maintain the order of the element for the lifetime. It does not chnage its order unless we do it.
1.Lists are Mutable/Changeable:
We can change the items in list with the help of item assignment. For example:
IndexErrorTraceback (most recent call last)<ipython-input-10-202c9277abcd>in<module>1 varlist = ["console","flare","python","data"]---->2 varlist[5]="Data Science"3print(varlist)IndexError:list assignment index out of range
3.Lists allows duplicate values:
List allows duplicate values, it can have as many duplicate values. For Example:
To understand above code better, Imagine a dictionary, the first value in dictionary is minimum and last value is maximum. 'console' comes before 'python' in dictionary.
max() and min() function does not work in mixed lists. Mixed lists mean A list with items of different category of data types.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-a0d202e95e64> in <module>
1 varlist = ["python","console","data",1,2,3]
----> 2 print(min(varlist))
3 print(max(varlist))
TypeError: '<' not supported between instances of 'int' and 'str'
var_list = [1,2,3,4,5,6,7,8,9]
present = 1 in var_list
print(present)
True
Iteration in list:
for loop is used to iterate over the list items. For example:
var_list = [1,2,3,4,5,6,7,8,9]
for i in var_list:
print(i)
123456789
Updating List items with the help of item assignment:
Lists are the most versatile data structures in Python since they are mutable, and their values can be updated by using the slice and assignment operator.n
list= [1,2,3,4,5,6] print(list)# It will assign value to the value to the second index list[2]=10print(list)# Adding multiple-element list[1:3]= [89,78] print(list)
[1,2,3,4,5,6][1,2,10,4,5,6][1,89,78,4,5,6]
List Methods:
Functions that are specific to list are known as list methods. We will go through each method one by one.
1.Adding elements to the list:
append() Python provides append() function which is used to add an element to the list. However, the append() function can only add value to the end of the list.
It does not return any value.
append() only takes one argument.
var_list = [1,2,3,4,5,6,7,8,9]
var_list.append(10) #it will add value at the end of the list , means at 9th index.
print(var_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If we append iterables(string, list,tuple,set,dictionary) in list. It will add iterables as whole at the end of the list. For Example:
var_list = [] #empty list
for i in range(5):
user_value = input(f"enter value for {i} index: ")
var_list.append(user_value)
print("List : ",var_list)
enter value for 0 index: 1
enter value for 1 index: 2
enter value for 2 index: 3
enter value for 3 index: 4
enter value for 4 index: 5
List : ['1', '2', '3', '4', '5']
2. extend() method:
The extend() method adds all the elements of an iterable (string,list, tuple, string,set) to the end of the list. extend() takes only one argument.For example:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-9b35c607c747> in <module>
1 varlist = [45,36,78,21,1,'python']
----> 2 varlist.sort()
3 print(varlist)
TypeError: '<' not supported between instances of 'str' and 'int'
These were all the methods that we are going to use in a list.
Deleting a list: del()
We can delete a list by using function del(). For example:
Now this list has been deleted , to show this better why don't we try to print list?
print(varlist)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-c07dcacb9080> in <module>
----> 1 print(varlist)
NameError: name 'varlist' is not defined
List Constructor - list():
List Constructor is used to convert an iterable(string,set,tuple,dictionary) into list. It has only one Parameter.
To Create a MultiDimensional List in Python , what we need first is Row and Column of multidimensional list.
row = int(input("Enter Row:"))
col = int(input("Enter Column:"))
Enter Row:2
Enter Column:3
Now we will need an empty list, so that we can populate it later with user values.
multi_dim = []
Now we need to iterate through rows and columns of list:
for i in range(row):
listitem = []
for j in range(col):
user_value = input(f"Enter Value for {i} row and {j} column : ")
listitem.append(user_value)
multi_dim.append(listitem)
print("MultiDimensional list : ",multi_dim)
Enter Value for 0 row and 0 column : 6
Enter Value for 0 row and 1 column : 4
Enter Value for 0 row and 2 column : 24
Enter Value for 1 row and 0 column : 1
Enter Value for 1 row and 1 column : -9
Enter Value for 1 row and 2 column : 8
MultiDimensional list : [['6', '4', '24'], ['1', '-9', '8']]
Now we need to represent this multidimensional list in matrix Form:
for i in multi_dim:
print(i)
['6', '4', '24']
['1', '-9', '8']
Another way to represent Multidimensional List in Matrix Form :
for i in range(row):
for j in range(col):
print(multi_dim[i][j],end=" ")
print()
6 4 24
1 -9 8
Transpose of a Matrix:
"Flipping" a matrix over its diagonal. The rows and columns get swapped.
Example: the value in the 1st row and 3rd column ends up in the 3rd row and 1st column.
multi_dim = [ [6,4,24],
[1,-9,8]
]
row = len(multi_dim)
col = len(multi_dim[0])
print("-------Original Matrix--------")
for i in multi_dim:
print(i)
1.first thing that we need to do, is to swap the row and column of the original matrix.
2.Second thing is to Create a Zero matrix of same Dimension.
T = []
rowT = col
colT = row
for i in range(rowT):
listitem = []
for j in range(colT):
listitem.append(0)
T.append(listitem)
for i in T:
print(i)
[0, 0]
[0, 0]
[0, 0]
Now to update values :
for i in range(rowT):
for j in range(colT):
T[i][j]=multi_dim[j][i]
for i in T:
print(i)
[6, 1]
[4, -9]
[24, 8]
This is the Transpose of the Matrix multi_dim.
Addition of Two Matrices:
The two matrices must be the same size,the rows must match in size, and the columns must match in size.
Example: a matrix with 3 rows and 5 columns can only be added to another matrix of 3 rows and 5 columns.
matrix_a = [[3,8],
[4,6]
]
matrix_b = [[4,0],
[1,-9]
]
add_matrix = [[0,0],
[0,0]
]
row = len(matrix_a)
col = len(matrix_a[0])
for i in range(row):
for j in range(col):
add_matrix[i][j]= matrix_a[i][j]+matrix_b[i][j]
for i in add_matrix:
print(i)
[7, 8]
[5, -3]
Multiplication of Two Matrices:
To multiply a matrix by another matrix we need to do the "dot product" of rows and columns ... what does that mean? Let us see with an example:
As You have noticed Multiplying 2∗∗3 Matrix with 3∗∗2 Matrix , gives us 2∗∗2 Matrix.
It means multiplying a list with dimension X Y with a list of dimension Y Z will result in a matrix of X * Z.
When we do Multiplication:
1.The number of columns of the 1st matrix must equal the number of rows of the 2nd matrix.
2.And the result will have the same number of rows as the 1st matrix, and the same number of columns as the 2nd matrix.
# Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
1.Take 10 integer inputs from user and store them in a list and print them on screen.
2.Take 20 integer inputs from user and print the following:
number of positive numbers
number of negative numbers
number of odd numbers
number of even numbers
number of 0s.
3.Write a program to print sum, average of all numbers, smallest and largest element of a list.
4.Make a list by taking 10 input from user. Now delete all repeated elements of the list.
E.g.-
INPUT : [1,2,3,2,1,3,12,12,32]
OUTPUT : [1,2,3,12,32]
5.Take a list of length n where all the numbers are non-negative and unique. Find the element in the list possessing the highest value. Split the element into two parts where first part contains the next highest value in the list and second part hold the required additive entity to get the highest value. Print the list where the highest value get splitted into those two parts.
Sample input: 4 8 6 3 2
Sample output: 4 6 2 6 3 2
6.Write a program to add and multiply two 3x3 matrices.