Let's say I have a list of fruits and i want to insert the elements of that list into another list. Using List comprehension I would have a code that looks like this:
fruit = ["apple", "orange", "banana", "peach"]
my_list = []
[my_list.insert(0, i) for i in fruit]
print(my_list)
This returns:
['peach', 'banana', 'orange', 'apple']
However, i want the elements arranged in the same order as the original list. My idea was just reversing it like this:
[my_list.insert(-1, i) for i in fruit]
But that returns for whatever reason:
['orange', 'banana', 'peach', 'apple']
Can somebody explain me why using the index [-1] results in this odd order? How could I achieve the original order?
EDIT:
I forgot to add that I'm looking for a method that inserts the list elements at the beginning of the list, so adding the elements of
more_fruit = ["pear", "pineapple", "coconut"]
in
my_list = ["apple", "orange", "banana", "peach"]
should result in
my_list = ["pear", "pineapple", "coconut", "apple", "orange", "banana", "peach"]
It is generally not recommended to use "side effects" within a list comprehension nor to use them in place of a for loop. You can insert a list into another list using simple subscripts however:
more_fruit = ["pear", "pineapple", "coconut"]
my_list = ["apple", "orange", "banana", "peach"]
my_list[0:0] = more_fruit
output:
print(my_list)
# ['pear', 'pineapple', 'coconut', 'apple', 'orange', 'banana', 'peach']
note: a subscript is a reference to some elements in the list, either a single element or a range of elements. In this case, we are replacing a range of elements containing zero elements starting at position 0.