How do I concatenate lists together?

Question

How do I concatenate lists together?

Answer

List concatenation works just like string concatenation - we just make use of the + operator! For example, if we had two lists:

my_first_list = [1, 2, 3]
my_second_list = [4, 5, 6]

I could concatenate them into a single, third list, like this:
my_combined_list = my_first_list + my_second_list

1 Like

how does python know it should not add the values of the first list and the second. for example if the first list consists of only one number [2] and y is [3] then:
list1 + list 2 should return 5.

1 Like

Python will not arithmetically add the values concatenated to the list. It will extend the list to include those values.

[1, 2, 3] + [9, 8, 7] => [1, 2, 3, 9, 8, 7]

The process of adding an array sequence is one of reduction, which means acting upon the list to reduce it to a single element with a sum. We can then set it as the value, and drop the list.

>>> a = [1, 2, 3, 9, 8, 7]
>>> while len(a) > 1:
    a[0] += a.pop(1)

    
>>> a[0]
30
>>> a = a.pop()
>>> a
30
>>> 
3 Likes

see we can also append the two together as it is easier and makes sense right?
here is the code!! enjoy
m = [1, 2, 3]
n = [4, 5, 6]

Add your code here!

def join_lists(x,y):
for i in range(len(x)):
x.append(y[i])
return x

print join_lists(m, n)