0% found this document useful (0 votes)
55 views11 pages

Python Lists: Python Ee - by Dr.M.Judith Leo, Hits

Python lists are versatile data types that can contain elements of different types. Lists are written with square brackets and elements are separated by commas. Individual elements can be accessed using indexes or sliced to access a range. Lists are mutable so their elements can be updated or deleted. Common operations on lists include concatenation, repetition, membership testing, and comparison. List comprehension provides a concise way to create lists. Built-in methods like append(), insert(), extend(), remove(), and pop() allow modifying lists in various ways.

Uploaded by

Rajesh Rajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views11 pages

Python Lists: Python Ee - by Dr.M.Judith Leo, Hits

Python lists are versatile data types that can contain elements of different types. Lists are written with square brackets and elements are separated by commas. Individual elements can be accessed using indexes or sliced to access a range. Lists are mutable so their elements can be updated or deleted. Common operations on lists include concatenation, repetition, membership testing, and comparison. List comprehension provides a concise way to create lists. Built-in methods like append(), insert(), extend(), remove(), and pop() allow modifying lists in various ways.

Uploaded by

Rajesh Rajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

11-03-2018

Python Lists

PYTHON EE - BY DR.M.JUDITH LEO, HITS 1

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.

list1 = ['physics', 'chemistry', 1997, 20.75]


list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
List4=[] # Empty list
PYTHON EE - BY DR.M.JUDITH LEO, HITS 2

1
11-03-2018

Accessing values in List


 Access individual item using indexing
• Index - integer, starts from 0.
• Accessing element out of index range - raise an IndexError.
• Negative indexing also allowed for list (-1 indicates last item)
Example: aa=[56,67,78,89]
>>> aa[3]
89
>>> aa[-3]
67

PYTHON EE - BY DR.M.JUDITH LEO, HITS 3

 Access range of elements using slicing (:)

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]

PYTHON EE - BY DR.M.JUDITH LEO, HITS 4

2
11-03-2018

Updating elements to a list

 Elements of a list be changed - mutable


 Use assignment operator = to change an item or range of items

Example aa= [56, 67, 78, 89, 96]


>>> aa[1]='apple'
>>> aa
[56, 'apple', 78, 89, 96]
>>> aa[2:4]=['orange','banana']
>>> aa
[56, 'apple', 'orange', 'banana', 96]

PYTHON EE - BY DR.M.JUDITH LEO, HITS 5

Deleting elements from a list

 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

PYTHON EE - BY DR.M.JUDITH LEO, HITS 6

3
11-03-2018

Basic List Operations


list1=[11,22,33,44,55,66,77]

Operator Description Example


+ Concatenation - Adds values on either side of >>> [1,2,3]+[4,5,6]
the operator [1, 2, 3, 4, 5, 6]
* Repetition – concatenates multiple copies of >>> [1,2,3]*2
the given list [1, 2, 3, 1, 2, 3]
[] Index - Gives the elements from the given list1[1] will give 22
index
[:] Range Slice – Returns list elements from the list1[1:4] will give [22,33,44]
given range
in Membership - Returns true if given item exists 44 in list1 returns True
in the list
not in Membership - Returns true if given item does 8 not in list1 returns True
not exist in the list

PYTHON EE - BY DR.M.JUDITH LEO, HITS 7

Traversing List Elements using a for Loop

• The elements in a Python list are iterable


• To traverse the list sequentially without using an index variable
fruits = ['banana', 'apple', 'mango']
for x in fruits:
print (x)

• To traverse the list sequentially by using an index variable


- Used to traverse the list in a different order or change the elements in the list

for x in range(len(fruits)): for x in range(0,len(fruits),2):


print (fruits[x]) #prints banana,apple,mango print (fruits[x]) #prints banana,mango

PYTHON EE - BY DR.M.JUDITH LEO, HITS 8

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

PYTHON EE - BY DR.M.JUDITH LEO, HITS 9

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

Built-in List Methods

1. append(element) list1=[11,22,33]
Adds single element to the end of the list >>> list1.append(44)
>>> list1
[11, 22, 33, 44]

2. insert(index, element) >>> list1


Insert an item at the defined index [11, 22, 55, 66]
index - position where element needs to be >>> list1.insert(2,33)
inserted >>> list1
element - the element to be inserted in the [11, 22, 33, 55, 66]
list

PYTHON EE - BY DR.M.JUDITH LEO, HITS 11

3. extend(list) >>> list1= [11, 22, 33, 44]


• Adds several elements to the list >>> list1.extend([55,66,77])
• Add all elements from one list to the >>> list1
another list [11, 22, 33, 44, 55, 66, 77]
>>> list2=[88,99]
>>> list1.extend(list2)
>>> list1
[11, 22, 33, 44, 55, 66, 77, 88, 99]
4. remove(element) list1=[11,22,33,44,55,66,77]
Removes an element from the list >>> list1.remove(44)
>>> list1
[11, 22, 33, 55, 66, 77]

PYTHON EE - BY DR.M.JUDITH LEO, HITS 12

6
11-03-2018

5. pop([index]) >>> list1= [11, 22, 33, 44]


• Removes and returns an element at >>> list1.pop(2)
the given index 33
• If index is not provided, removes and >>> list1
returns the last item [11, 22, 44]
>>> list1.pop()
44
>>> list1
[11, 22]
6. index(element) >>> list1
Returns the index of the first matched [11, 22, 33, 55, 66]
item >>> list1.index(55)
3

PYTHON EE - BY DR.M.JUDITH LEO, HITS 13

7. count(element) >>> list1.count(55)


Returns the count of given element 1
8. sort() >>> list=[67,'orange',45,'apple']
Sort items in a list in ascending order. >>> list.sort()
>>> list
[45, 67, 'apple', 'orange']
9. reverse() >>> list1
Reverse the order of items in the list [11, 22, 33, 55, 66]
>>> list1.reverse()
>>> list1
[66, 55, 33, 22, 11]

PYTHON EE - BY DR.M.JUDITH LEO, HITS 14

7
11-03-2018

Built-in List Functions


1. len(list) >>> list1
Return the length (the number of items) in [66, 55, 33, 22, 11]
the list. >>> len(list1)
5
2. max(list) >>> list
Returns the largest item in the list. [45, 67, 'apple', 'orange']
>>> max(list)
'orange'
3. min(list) >>> min(list)
Returns the smallest item in the list 45
4. sum(list) >>> list1
Returns the sum of all elements in the list. [66, 55, 33, 22, 11]
>>> sum(list1)
187
PYTHON EE - BY DR.M.JUDITH LEO, HITS 15

5. list(iterable) >>> tup


Converts an iterable (tuple, string, set, (1, 2, 3, 4)
dictionary) to a list. >>> list(tup)
[1, 2, 3, 4]
>>> dict={'aa':101,'bb':102}
>>> list(dict)
['aa', 'bb']

PYTHON EE - BY DR.M.JUDITH LEO, HITS 16

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

Matrix – Two Dimensional List

 a matrix is implemented as nested list (list inside a list).


 each element in the list - row of the matrix.
Example X = [[1, 2], [4, 5], [3, 6]] #represent a 3x2 matrix.
>>> X[0] #First row can be selected as X[0]
[1, 2]
>>> X[1][0] #Element in second row, first column is selected
4

PYTHON EE - BY DR.M.JUDITH LEO, HITS 18

9
11-03-2018

# Program to add two matrices using nested loop

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)

PYTHON EE - BY DR.M.JUDITH LEO, HITS 19

Initializing Matrix with Console Input Values


O/P:
matrix = [] # Create an empty list
Enter the number of rows: 2
nRows = eval(input("Enter the number of rows: "))
nColumns = eval(input("Enter the number of columns: ")) Enter the number of columns: 3
for row in range(nRows): Enter an element and press Enter: 1
matrix.append([]) # Add an empty new row Enter an element and press Enter: 2
for column in range(nColumns): Enter an element and press Enter: 3
value = eval(input("Enter an element and press Enter: ")) Enter an element and press Enter: 4
matrix[row].append(value) Enter an element and press Enter: 5
print(matrix)
Enter an element and press Enter: 6
[[1, 2, 3], [4, 5, 6]]

PYTHON EE - BY DR.M.JUDITH LEO, HITS 20

10
11-03-2018

Initializing Matrix with Random Values


import random as rd
matrix = [] # Create an empty list
nRows = eval(input("Enter the number of rows: ")) O/P:
nColumns = eval(input("Enter the number of columns: "))
for row in range(nRows): Enter the number of rows: 3
matrix.append([]) # Add an empty new row Enter the number of columns: 4
for column in range(nColumns): [39, 55, 84, 80]
matrix[row].append(rd.randint(0,99)) [91, 87, 23, 89]
for r in matrix:
print(r) [80, 83, 94, 25]

PYTHON EE - BY DR.M.JUDITH LEO, HITS 21

# Program to multiply two matrices using nested loop


X = [[12,7,3], [4 ,5,6], [7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0], O/P:
[0,0,0]] [114, 160, 60]
[74, 97, 73]
# iterate through rows of X [119, 157, 112]
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)

PYTHON EE - BY DR.M.JUDITH LEO, HITS 22

11

You might also like