Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list concatenation with add function used

I just realized a problem, when I try to use "+" in a list concatenation situation.

For example I can do:

print([[1] + [5]* n for n in range(1, 4)])
>>> [[1, 5], [1, 5, 5], [1, 5, 5, 5]]

But if I switch the sequence of the add function:

print([[5] * n for n in range(1, 4) + [1]])

I won't get:

>>> [[5, 1], [5, 5, 1], [5, 5, 5, 1]]

Instead I got: TypeError: unsupported operand type(s) for +: 'range' and 'list'

Is there anyway to make it work?

like image 480
jxie0755 Avatar asked Sep 22 '26 07:09

jxie0755


1 Answers

You are doing this operation:

range(1, 4) + [1]

Which doesn't mean anything in this case.

You have to do the + [1] right after the [5] * n as in:

print([[5]*n+[1] for n in range(1, 4)])
like image 107
ggrelet Avatar answered Sep 23 '26 21:09

ggrelet