Why can't I use [ ] when concatenating 2 lists?

Question: Why can’t I use [ ] when concatenating 2 lists in Python? It does not give me any error, but it does not bring the expected result.

**Context:**I was trying to solve an exercise where I had to concatenate 2 lists in Python. First there are 2 variables (x & y; the variables contain one object each) which go into 2 lists (x_list & y_list). I have to multiply them by 10 so the contents of x_list & y_list becomes 10 objects each. In that sense when I concatenate these 2 list to one big_list and count how many objects are there, there should be 20. However, a different result comes up.

``````x = object()
y = object()

# TODO: change this code
x_list = [x]*10
y_list = [y]*10
big_list = [x_list + y_list]  #This line is the main problem

print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))
``````

The Output:

``````    x_list contains 10 objects
y_list contains 10 objects
big_list contains 1 objects
``````

Solution I tried: After playing around with the code a little bit and reading on a little bit on concatenating 2 lists in Python, I noticed that when concatenating 2 lists they didn’t use [ ]. So I tried the solution below:

``````x = object()
y = object()

# TODO: change this code
x_list = [x]*10
y_list = [y]*10
big_list = x_list + y_list

print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))
``````

Here was the output:

``````    x_list contains 10 objects
y_list contains 10 objects
big_list contains 20 objects
``````

Now my question is, why did a simple [ ] made such a big difference? I read once that if you don’t use " " in strings then Python interprets it as a variable that’s why sometimes it can show errors like NameError. So is there something like this here as well? The interpreter interprets it as something else rather than list concatenation?

Thank you
Joyeta

`[x_list + y_list]` does concatenate `x_list` with `y_list`, but the outer `[]` puts that into another list. So the concatenated list containing `20` elements can be accessed with `big_list[0]`.

So basically, Python concatenates these 2 list, creates a list containing 20 objects & then puts that list into the big_list? That’s why the big_list seems to contain only that one object?

Yep, that one element within `big_list` is list, containing the result of `x_list + y_list`.

1 Like

Thank you so much for your help.

1 Like

Joyeta:
In such case you may use print(big_list) or typing big_list in a new cell of notebook to see what’s inside the list.

1 Like