Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

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.

Start empty, then add each item you want to keep.
In code
result = []
for x in nums:
    if x > 0:
        result.append(x)
return result

Keep 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.

Keep some: append inside the if. Change all: append every time.
Keeping the positive numbers
3
0
-1
1
4
2
-5
3
6
4
x
x
3
result
[3]

The new list starts empty. 3 is positive, so append it.

Move 1 of 5