Python: How to add to list in loop

In this tutorial, we'll learn:

  1. How to loop through a list and add its items to the end of another list 
  2. How to loop through a list and add its items to the beginning of another list 
  3. How to check before adding 

Loop through a list and add it to the end of another list 

Let's see an example:

list_1 = ["a", "b", "c"]
list_2 = [1, 2, 3]

# Loop through list_2
for i in list_2:
    # add to the end of list_1
    list_1.append(i)

# Print list_1
print(list_1)

Output:

['a', 'b', 'c', 1, 2, 3]

Here, we've:

  1. Loop through list_2
  2. Add list_2's items to the end of list_1  by using the append method
  3. Print list_1

Loop through a list and add to the beginning of another list 

In the following example, we'll see how to loop through a list and add items to the beganning end of another list.

list_1 = ["a", "b", "c"]
list_2 = [1, 2, 3]

# loop through list_2
for i in list_2:
    # add to the end of list_1
    list_1.insert(0, i)

# Print list_1
print(list_1)

Output:

[3, 2, 1, 'a', 'b', 'c']

In this example, we've used the insert method to add items to the end of the list.

Loop and Check before adding to a list

We'll see how to check before adding an item greater than 1 to another list in this example.

list_1 = ["a", "b", "c"]
list_2 = [1, 2, 3]

# loop through list_2
for i in list_2:
    # Check if number is greater than 2
    if i > 2:
        # Append to my_list
        list_1.append(i)

# Print list_1
print(list_1)

Output:

['a', 'b', 'c', 3]

As you can see, the program added 3 to list_1.