append a list with each element from a list in python

To append a list with each element from another list, you can use a for loop to iterate over the elements in the second list and append them one by one to the first list using the append method. Alternatively, you can use the extend method of the first list to add all the elements from the second list at once.

Here is an example using both methods:

main.py
# using a for loop and append method
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for element in list2:
    list1.append(element)
print(list1)  # Output: [1, 2, 3, 4, 5, 6]

# using extend method
list3 = [7, 8, 9]
list1.extend(list3)
print(list1)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
277 chars
12 lines

In the first example, we created two lists list1 and list2 and used a for loop to iterate over the elements in list2 and append them one by one to list1. In the second example, we created another list list3 and used the extend method of list1 to add all the elements from list3 at once.

gistlibby LogSnag