0% found this document useful (0 votes)
6 views

Lab_6_List_std1 (1)

Uploaded by

sherlockalt3
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lab_6_List_std1 (1)

Uploaded by

sherlockalt3
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

List

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

 Good thing is..


 THE ITEMS IN THE LIST NEED NOT BE OF SAME
TYPE
Creating a list
 Creating an EMPTY  Creating a list with items
list listname = [item1, item2, ….]
listname = []
Example:
Example: Temp = [100, 99.8, 103, 102]
L1 = [] S = [’17MIS0001’, ‘Arun’, 99.9]
MyList = []
L2 = [1, 2, 3, 4, 5, 6, 7]
Books = []
Course = [‘Python’, ‘C’, ‘C++’, ‘Java’]
Accessing Values
• Using index or indices
>>>L1 = [1, 2, 3, 4, 5, 6]
>>>print (L1[3]) #indexing
>>>4
>>>print (L1[2:5]) #slicing
>>>[3, 4, 5]
>>> x=list(“123456")
>>> x
[‘1', ‘2', ‘3', ‘4‘, ’5’, ’6’]
Updating Elements
 Update an element in list using index
>>>L1 = [1, 2, 3, 4, 5, 6]
>>>L1[2] = 111
>>>L1
[1, 2, 111, 4, 5, 6]
Deleting Elements
 Delete an element in list using index
>>>L1 = [1, 2, 3, 4, 5, 6]

>>>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]

 >>> x2=['Ni!'] * 4 # Repetition


 >>>x2

 ['Ni!', 'Ni!', 'Ni!', 'Ni!']


Basic Operations in List
 >>> [1, 2] + list("34")
# Same as [1, 2] + ["3", "4"]
[1, 2, '3', '4‘]
 >>> [1, 2] + ["34“]
[1, 2, ‘34‘]

>>> mylist=[1, 2] + list("34")


>>>print(mylist)
[1, 2, '3', '4‘]
>>> x=list("ramu")
>>> x
['r', 'a', 'm', 'u']
List Iteration
 >>> 3 in [1, 2, 3] # Membership
True
 >>> 4 in [1, 2, 3] # Membership
False list1=[1,2,3]
 >>> for x in [1, 2, 3]:
for x in list1:
print(x, end=' ') print(x,end=' ')
123
123
List Comprehensions
>>> res = [c * 4 for c in 'SPAM']
# List comprehensions
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']
 expression is functionally equivalent to a for
loop that builds up a list of results manually
 list comprehensions are simpler to code and
likely faster to run today:
List Comprehensions
# List comprehension equivalent ...
>>> res = [] x=[10]
for c in 'spam':
>>> for c in 'SPAM': x.append(c*4)
res.append(c * 4) print(x)
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM'] [10,'SSSS', 'PPPP', 'AAAA',
'MMMM']
Indexing, Slicing
>>> L = ['spam', 'Spam', 'SPAM!‘,’SpaM’]

>>> L[2] # Offsets start at zero

'SPAM!'

>>> L[−2] # Negative: count from the right

'Spam!'

>>> L[1:] # Slicing fetches sections

['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

>>> L.sort(key=str.lower, reverse=True)

# Change sort order


>>> L ['aBe', 'ABD', 'abc']
Other common list methods
>>> L = [1, 2]
>>> L.extend([3, 4, 5])
# Add many items at end (like in-place +)
>>> L [1, 2, 3, 4, 5]

# Delete and return last item


>>> L.pop()
5
Other common list methods
>>> L
[1, 2, 3, 4]
>>> L.reverse() # In-place reversal method
>>> L
[4, 3, 2, 1]
>>> list(reversed(L)) # Reversal built-in with a result
(iterator)
[1, 2, 3, 4]
Other common list methods
>>> L = ['spam', 'eggs', 'ham']
# Index of an object (search/find)
>>> L.index('eggs')
1

>>> L.insert(1, 'toast') # Insert at position


>>> L
['spam', 'toast', 'eggs', 'ham']

>>> L.remove('eggs') # Delete by value


>>> L
['spam', 'toast', 'ham']
Other common list methods

>>>L=['spam', 'toast', 'ham']


>>> L.pop(1) # Delete by position 'toast'
>>> L
['spam', 'ham']
>>> L.count('spam') # Number of occurrences
1
Other common list methods

>>> L = ['spam', 'eggs', 'ham', 'toast']


>>> del L[0] # Delete one item
>>> L
['eggs', 'ham', 'toast']
>>> del L[1:] # Delete an entire section
>>> L # Same as L[1:] = []
['eggs‘]
Other common list methods
>>> L = ['Already', 'got', 'one']
>>> L[1:] = []
>>> L
['Already']
>>> L[0] = []
>>> L
[[]]
Hence…
 A list is a sequence of items stored as a single
object.
 Items in a list can be accessed by indexing, and
sub lists can be accessed by slicing.
 Lists are mutable; individual items or entire slices
can be replaced through assignment statements.
 Lists support a number of convenient and
frequently used methods.
 Lists will grow and shrink as needed.
Python Programming, 1/e 27
Strings and Lists
>>> S = 'spammy'
>>> L = list(S)
>>> L
['s', 'p', 'a', 'm', 'm', 'y']
>>> L[3] = 'x' # Works for lists, not strings
>>> L[4] = 'x‘
>>> L
['s', 'p', 'a', 'x', 'x', 'y']
>>> S = “”.join(L) #uses ‘’” for joining elements of list
>>> S
'spaxxy‘
Strings and Lists
>>> ‘#'.join(['eggs', 'sausage', 'ham', 'toast'])
s='eggs#sausage#ham#toast‘
# uses ‘SPAM’ for joining elements of list
>>> line = 'aaa bbb ccc'
>>> cols = line.split()
>>> cols
['aaa', 'bbb', 'ccc']
Get a list as input from user
# creating an empty list
lst = []

# number of elemetns as input


n = int(input("Enter number of elements : "))

# iterating till the range


for i in range(0, n):
ele = input()
lst.append(ele) # adding the element

print(lst)
Problem

A farmer with a fox, a goose, and a sack of corn needs to cross


a river. Now he is on the east side of the river and wants to go
to west side. The farmer has a rowboat, but there is room for
only the farmer and one of his three items. Unfortunately, both
the fox and the goose are hungry. The fox cannot be left alone
with the goose, or the fox will eat the goose. Likewise, the
goose cannot be left alone with the sack of corn, or the goose
will eat the corn. Given a sequence of moves find if all the
three items fox, goose and corn are safe. The input sequence
indicate the item carried by the farmer along with him in the
boat. ‘F’ – Fox, ‘C’ – Corn, ‘G’ – Goose, N-Nothing. As he is now
on the eastern side the first move is to west and direction
alternates for each step.
Pseudocode
READ items_carried
SET east as G, C, F
SET west as empty
SET from_Dir = east and to_Dir = west
FOR each item in items_carried
IF from_Dir == east THEN
remove item from east and add to west
IF east or west contains ‘C’ and ‘G’ or ‘G’ and ‘F’ THEN
PRINT ‘NOT SAFE’
BREAK
ELSE
remove item from west and add to east
IF east or west contains ‘C’ and ‘G’ or ‘G’ and ‘F’ THEN
PRINT ‘NOT SAFE’
BREAK
END IF
IF from_Dir == east THEN
SET from_Dir = west
SET to_Dir = east
ELSE
SET from_Dir = east
SET to_Dir = west
END IF
END FOR
PRINT ‘SAFE’

You might also like