EC1002E Intro Programming Slides Week5 Lists and Operations
EC1002E Intro Programming Slides Week5 Lists and Operations
Check Length
Check +,*, in
Lists: Nesting and Comprehension
Nesting of Lists
Eg: A matrix, m = [[11,12,13],[21,22,23],[31,32,33]]
Indexing, Slicing with nested lists
Eg: m[0], m[0][0],
m[0][1], m[1][0]
m[1][-1], m[-1][-1]
l.append([‘4’,’5’,’6’]) vs l.extend([‘4’,’5’,’6’])
Lists: Removing Elements
Lists can grow and shrink on demand while preserving the order
Three methods are available: pop(index), remove(item), del list[index]
Eg: l = [1,2,3]
pop(index): l.pop(0) # Remove one item at specified index and return the item
l.pop() # Remove one item from end of list (-1) and return the item
remove(item): l.remove(‘1’) # Remove a specific item based on value
What is multiple elements have same value or if no element has the value?
del list[index]: del l[2] # Remove a specific item from list based on location
del l # Removes the list ‘l’
Lists: Extended Operations
clear(): Remove all items from list and make it empty
Eg: l=[1,2,3]
l.clear()