简体   繁体   中英

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?

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: int s are immutable , and usually small int s, are singletons: there is at all time only one zero 0 int in Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM