Professional Documents
Culture Documents
Python Lists
Introduction
Most versatile datatype
Written as a list of comma-separated values (items) between square
brackets.
Items in a list need not be of the same type.
1
11-03-2018
Example aa=[56,67,78,89,96]
>>> aa[2:]
[78, 89, 96]
>>> aa[1:4]
[67, 78, 89]
>>> aa[-5:-1]
[56, 67, 78, 89]
>>> aa[::-1]
[96, 89, 78, 67, 56]
2
11-03-2018
can delete one or more items from a list or entire list using the keyword del
Example list1 =[11, 22, 33, 44, 55, 66, 77, 88]
>>> del list1[4]
>>> list1
[11, 22, 33, 44, 66, 77, 88]
>>> del list1[2:4]
>>> list1
[11, 22, 66, 77, 88]
>>> del list1
>>> list1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'list1' is not defined
3
11-03-2018
4
11-03-2018
Comparing Lists
Lists are compared using the comparison operators (>, >=, <=, ==, and !=).
The two lists must contain the same type of elements for comparison.
The comparison uses lexicographical ordering:
• The first two elements are compared, and if they differ this determines the
outcome of the comparison;
• if they are equal, the next two elements are compared, and so on.
>>> list1 = ["green", "red", "blue"]
>>> list1>list2
>>> list2 = ["red", "blue", "green"]
False
>>> list1==list2
>>> list2<=list1
False
False
>>> list1!=list2
>>> list2<>list1
True
True
List Comprehension
provides a concise way to create a sequential list.
consists of brackets containing
• an expression
• followed by a for clause,
• then zero or more for or if clauses.
produces a list with the results from evaluating the expression.
>>> list1 = [x for x in range(5)]
>>> list1
[0, 1, 2, 3, 4]
>>> list2 = [x*.5 for x in range(5)]
>>> list2
[0.0, 0.5, 1.0, 1.5, 2.0]
>>> list3 = [x*2 for x in list2 if x>1]
>>> list3
[3.0, 4.0]
PYTHON EE - BY DR.M.JUDITH LEO, HITS 10
5
11-03-2018
1. append(element) list1=[11,22,33]
Adds single element to the end of the list >>> list1.append(44)
>>> list1
[11, 22, 33, 44]
6
11-03-2018
7
11-03-2018
8
11-03-2018
Inputting Lists
• To read data from the console into a list
list = [] # Create a list s=input("Enter items in single line with space ")
n=eval(input("Enter size of list: ")) items=s.split()
print("Enter the elements ") list=[eval(i) for i in items]
for i in range(n): print(list)
list.append(eval(input()))
print(list)
O/P:
Enter size of list: 4
Enter the elements O/P:
1 Enter items in a single line with space 1 2 3 4 5 6 6
2 [1, 2, 3, 4, 5, 6, 6]
3
4
[1, 2, 3, 4]
PYTHON EE - BY DR.M.JUDITH LEO, HITS 17
9
11-03-2018
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]] Output:
Y = [[5,8,1], [6,7,3], [4,5,9]] [17, 15, 4]
[10, 12, 9]
result = [[0,0,0], [0,0,0],[0,0,0]] [11, 13, 18]
for i in range(len(X)):
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print (r)
10
11-03-2018
11