user6395009
user6395009

Reputation:

Inserting values into specific indices in a list in Python

I have two lists:

l1 = [254, 255, 254, 254, 254, 254, 255, 255, 254]
l2 = [(255, 255, 255, 0), (255, 255, 255, 0), (255, 255, 255, 0)]

I want to modify l1 and insert 0s from l2 into indexes 3, 7 and 11 so l1 would look like this:

[254, 255, 254, 0, 254, 254, 254, 0, 255, 255, 254, 0]

It works when I use this code:

l1.insert(3, l2[0][-1])
l1.insert(7, l2[1][-1])
l1.insert(11, l2[2][-1])

But when I try doing it without insert() function:

l1 = l1[:3] + l2[0][-1] + l1[3:]
l1 = l1[:7] + l2[1][-1] + l1[7:]
l1 = l1[:11] + l2[2][-1] + l1[11:]

I get an error:

TypeError: can only concatenate list (not "int") to list

What am I doing wrong?

Upvotes: 1

Views: 54

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476544

Well the problem is that you use + to concatenate lists, but here you do not concatenate lists, you concatenate a list with an int with a list. Indeed:

l1 = l1[:3] + l2[0][-1] + l1[3:]
#    ^ list   ^ int       ^ list

You can solve the issue by making the second argument a list (for instance by surrounding it with square brackets):

l1 = l1[:3] + [l2[0][-1]] + l1[3:]
#    ^ list   ^ list        ^ list

Nevertheless it is better to use insert: it is less error-prone (we can assume that it is tested effectively) and furthermore usually more efficiently (since the insertion is done inplace).

Finally note that if you insert 0, it does not matter where that 0 originates from: ints are immutable, and usually small ints, are singletons: there is at all time only one zero 0 int in Python.

Upvotes: 5

Related Questions