Lab_6_List_std1 (1)
Lab_6_List_std1 (1)
Introduction
Contains multiple values that are logically related
List is a type of mutable sequence in Python
Each element of a list is assigned a number –
index / position
Can do indexing, slicing, adding, multiplying, and
checking for membership
Built-in functions for finding length of a sequence
and for finding its largest and smallest elements
What is a List?
Most versatile data type in Python
Comma-separated(,) items can be collected in
square brackets
>>>del(L1[4])
>>>L1
[1, 2, 3, 4, 6]
Basic Operations in List
>>> len([1, 2, 3]) # Length
3
>>> X1=[1, 2, 3] + [4, 5, 6] # Concatenation
[1, 2, 3, 4, 5, 6]
'SPAM!'
'Spam!'
['Spam', 'SPAM!‘,’SpaM’]
Matrixes
a basic 3 × 3 two-dimensional list-based array:
>>>matrix=[1,2,3]
>>> matrix = [[1, 2, 3, 4], [4, 5, 6], [7, 8, 9]]
1 2 3 4
4 5 6
5 7 8
>>>matrix[0][3] -> 4
With one index, you get an entire row (really, a
nested sublist), and with two, you get an item
within the row:
Matrixes
mymatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> mymatrix[1]
[4, 5, 6] >>>mymatrix[0]
>>> mymatrix[1][1]
[1,2,3]
5
>>>mymatrix[0][0]
>>> mymatrix[2][0]
1
7
>>>mymatrix[0][2]
>>> mymatrix = [[1, 2, 3],
[4, 5, 6],
3
[7, 8, 9]]
>>> mymatrix[1][2]
Insertion, Deletion and Replacement
>>> L = [11, 22, 33]
>>>L[1:2]
22
>>> L[1:2] = [4, 5] # Replacement/insertion
>>> L
[11, 4, 5, 33]
>>> L[1:1] = [6, 7] # Insertion (replace nothing)
>>> L
[11, 6, 7, 4, 5, 3]
>>> L[1:2] = [] # Deletion (insert nothing)
>>> L
[1, 7, 4, 5, 3]
Insertion, Deletion and Replacement
>>> L = [1]
# Insert all at :0, an empty slice at front
>>> L[:0] = [2, 3, 4]
>>> L
[2, 3, 4, 1]
# Insert all at len(L):, an empty slice at end
>>> L[len(L):] = [5, 6, 7]
>>> L
[2, 3, 4, 1, 5, 6, 7]
List method calls
# Append method call: add item at end
>>> L = ['eat', 'more', 'SPAM!']
>>> L.append('please')
>>> L
['eat', 'more', 'SPAM!', 'please']
>>> L.sort() # Sort list items ('S' < 'e')
>>> L
['SPAM!', 'eat', 'more', 'please']
More on Sorting Lists
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort() # Sort with mixed case
>>> L
['ABD', 'aBe', 'abc']
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort(key=str.lower) # Normalize to lowercase
>>> L
['abc', 'ABD', 'aBe']
More on Sorting Lists
print(lst)
Problem