Previous Lecture Lecture 13 Next Lecture

Lecture 13, Tue 02/20

More on Lists

Recorded Lecture: 2_20_24

More on Lists

print(list({1, 2, 3})) # set to a list of ints
print(list((1, 2, 3))) # tuple to a list of ints
print(list({"1":10, "2":20, "3":30})) # dict to a list of its keys (strings)
print(list("123")) # string to a list of characters (strings)

List Operations / Methods

Some examples of operations that won’t do an in-place modification, but provide a copy of the updated list:

list1 = [1,2]
list2 = ['a', 'b']
print(list1 + list2) # [1, 2, 'a', 'b']
print(list2 + list1) # ['a', 'b', 1, 2]
print(list1) # [1, 2]
print(list2) # ['a', 'b']
list1 = [10, 20, 30, 40]
print(list1[1:3]) # [20, 30]
print(list1[-3:-1]) # [20, 30]
print(list1[1:]) # [20, 30, 40]
print(list1[:3]) # [10, 20, 30]
print(list1[:]) # [10, 20, 30, 40]
print(list1[0:4:2]) # [10, 30]
print(list1) # [10, 20, 30, 40]
list1 = [30, 20, 40, 10] 
print(sorted(list1)) # [10, 20, 30, 40]
print(list1) # [30, 20, 40, 10]
print(sorted(list1, reverse=True)) # [40, 30, 20, 10]
print(list1) # [30, 20, 40, 10]
list1 = [30, 20, 40, '10']
print(sorted(list1)) # ERROR (can’t compare int and str)

Some examples of list methods that do an in-place modification of the list

list1 = [10, 20, 30, 40]
print(list1.append(50)) # None
print(list1) # [10, 20, 30, 40, 50]
list1 = [10, 20, 30, 40]
list2 = ['a', 'b']
print(list1.extend(list2)) # None
print(list1) # [10, 20, 30, 40, 'a', 'b']
list1 = [10, 20, 30, 40]
print(list1.insert(2, 25)) # None
print(list1) # [10, 20, 25, 30, 40]
list1 = [10, 20, 30, 40, 30]
print(list1.remove(30)) # None
print(list1) # [10, 20, 40, 30]
print(list1.pop()) # 30
print(list1) # [10, 20, 40]
print(list1.pop(1)) # 20
print(list1) # [10, 40]
list1 = [30, 20, 40, 10]
print(list1.sort()) # None
print(list1) # [10, 20, 30, 40]
print(list1.sort(reverse=True)) # None
print(list1) # [40, 30, 20, 10]

Common calculations on lists

def ourMax(collection):
	if collection == []:
		return None

	maxElement = collection[0]
	for item in collection:
		if item > maxElement:
			maxElement = item

	return maxElement

list1 = [30, 20, 40, 10]
print(ourMax(list1)) # 40
list1 = [30, 20, 40, 10] # change 10 to "10" to see an error
print(max(list1)) # 40
list1 = [30, 20, 40, 10]
print(min(list1)) # 10
print(sum(list1)) # 100

A note on how Python interprets True and False

# change to 0, None, [], (), {} to see x is False
# change to any other value to see x is True
x = False 

if x:
	print("x is True")
else:
	print("x is False")