Python List Methods

Question Click to View Answer

What does the following code print to the console.

nums = [1, 2, 3, 4, 1, 4, 1]
print(nums.count(1))

3 is printed.

The count method returns the number of times an element is in a list.

What does the following code print to the console.

cities = ["boston", "philly", "LA"]
print(len(cities))

3 is printed.

The Python len function returns the number of items in a list.

What does the following code print to the console.

doubles = [22, 11, 66]
doubles.sort()
print(doubles)

[11, 22, 66] is printed.

The sort() method rearranges the numbers in a list in ascending order.

What does the following code print to the console.

foods = ["pizza", "pie", "ham"]
foods.reverse()
print(foods)

['ham', 'pie', 'pizza'] is printed.

The reverse() method reverses the items in a list.

What does the following code print to the console.

stuff = ["a", "b", "c"]
stuff.insert(1, "water")
print(stuff)

['a', 'water', 'b', 'c'] is printed.

The insert() method is used to add the "water" string in position 1 of the stuff list.

What does the following code print to the console.

bases = ["first", "second", "third", "fourth"]
bases.remove("fourth")
print(bases)

['first', 'second', 'third'] is printed.

The remove() method deletes an item from a list.

What does the following code print to the console.

digits = [1, 4, 2, 8, 1]
digits.remove(1)
print(digits)

[4, 2, 8, 1] is printed.

The remove() method only delete the first matching item in a list. It does not delete all of the matching items.

What does the following code print to the console.

flowers = ["rose", "tulip"]
flowers.clear()
print(flowers)

[] is printed.

The clear() method deletes all items in a list.

What does the following code print to the console.

letters = ["b", "a", "y", "a"]
index = letters.index("a")
print(index)

1 is printed.

The index() method prints the index of the first occurrence of an item in a list. The string "a" is in positions 1 and 3. The index() method returns 1 in this example because that's the index of the first "a" in the list.

What does the following code print to the console.

numbers = [1, 2, 3]
pos = numbers.index(44)
print(pos)

This code raises a ValueError: 44 is not in list error.

When the index() method cannot find an item in a list, it raises an error.

What does the following code print to the console.

odds = [1, 3, 5, 7]
odds.pop()
print(odds)

[1, 3, 5] is printed.

The pop() method removes the last element from a list.

What does the following code print to the console.

evens = [2, 4, 6]
last_num = evens.pop()
print(last_num)

6 is printed.

The pop() method returns the last element in a list and removes the last element from a list.