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