I am just starting to learn python, I was trying out some code and I wanted to ask why the two following codes function differently?
First code sample:
def combine_lists(list1, list2):
new_list = list2
index = len(list2)
for items in list1:
new_list.insert(index, items)
return(new_list)
Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
Drews_list = ["Mike", "Carol", "Greg", "Marcia"]
print(combine_lists(Jamies_list, Drews_list))
The output of this first code is correct (where I want list 1 reversed):
['Mike', 'Carol', 'Greg', 'Marcia', 'Peter', 'Jan', 'Bobby', 'Cindy', 'Alice']
Second code sample:
def combine_lists(list1, list2):
new_list = list2
for items in list1:
new_list.insert(len(list2), items)
return(new_list)
Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
Drews_list = ["Mike", "Carol", "Greg", "Marcia"]
print(combine_lists(Jamies_list, Drews_list))
But this second code outputs:
['Mike', 'Carol', 'Greg', 'Marcia', 'Alice', 'Cindy', 'Bobby', 'Jan', 'Peter']
Why is there a difference in these two outputs by just assigning the len(list2) to a variable and using that for the index insertion?
Thanks!