Lists
Computer Science · Python
Question 1 of 10
0What does this Python code print? nums = [9, 3, 4] print(len(nums))
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Lists explained
A list is an ordered collection of items written in square brackets, such as [3, 1, 4]. Lists are mutable, so you can change them after they are created. A list can hold items of different types and can grow or shrink as the program runs. Like strings, lists are indexed from 0, and negative indexes count from the end.
Common methods change a list in place. append(x) adds an item to the end, insert(i, x) places an item at index i, and remove(x) deletes the first item equal to x. pop() removes and returns the last item, or the item at a given index. sort() puts the items in order and returns None, so do not write nums = nums.sort(). The built-in sorted() returns a new sorted list and leaves the original alone.
The in operator checks whether an item is present, and len() gives the number of items. Assignment does not copy a list: b = a gives two names for the same list, so a change through one name is visible through the other. Use a.copy() or a[:] to make an independent copy.
nums = [3, 1, 4]
nums.append(1)
nums.remove(4)
nums.sort()
print(nums, len(nums))
Worked example
Trace the program above.
- Start with [3, 1, 4].
- append(1) adds 1 at the end: [3, 1, 4, 1].
- remove(4) deletes the first 4: [3, 1, 1].
- sort() puts the items in order: [1, 1, 3].
- print displays the list and its length: [1, 1, 3] 3.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this Python code print? nums = [1, 3, 2] print(len(nums))
Medium
What does this Python code print? nums = [8, 6, 9] print(nums[2])
Hard
What does this Python code print? nums = [6, 13, 1, 10] nums.append(4) nums.pop(0) print(nums[-2])