Making a new list
Build a new list by adding the items you want, one at a time. About 9 minutes.
An empty list to fill
Often a question asks you to return a list: the numbers that pass a test, or the numbers changed in some way. To build one, start with an empty list, which is just a pair of square brackets with nothing inside. Then add items to the end, one at a time.
Adding an item to the end of a list is called appending. Each language has its own way to write it. When the loop is done, the list holds everything you added, in the order you added it.
result = []
for x in nums:
if x > 0:
result.append(x)
return resultKeep some, change all
There are two common jobs. The first is to keep only some of the items, such as the positive numbers. You put the add inside the if, and items that fail the test are left out.
The second is to change every item, such as adding 5 to each. Then there is no test, and you add a changed copy of every item. In both jobs the original list is never altered. You make a brand new one and return that.
- x
- 3
- result
- [3]
The new list starts empty. 3 is positive, so append it.
nums is [2, -3, 5]. You build a new list of only the positive numbers. How many items does the new list have?
- A2
- B3
- C1
Show the answer
2. Only 2 and 5 are positive, so the new list is [2, 5].
Positives only
Return a new list holding only the positive numbers (bigger than 0) from the list, in the same order. Zero is not positive.
nums = [3, -1, 4, 0, -5, 6] → [3, 4, 6]
0 ≤ length of nums ≤ 100,000 · −1,000,000 ≤ nums[i] ≤ 1,000,000