简体   繁体   中英

Insert in a for loop gives me an infinite loop, and can't insert what I want where I want

I'm trying to insert different elements in specific indexes of a list.

Given this example:

l = [1,2,3,4,5]

Lets say I want to systematically insert the string 'k' after each value of the list. For this, I know I can use enumerate:

r = l.copy()
for idx, val in enumerate(l):
    r.insert(idx, 'k')

or do it manually with a counter:

index = 0
for i in l:
    index += 1
    l.insert(index, 'k')
    print(index)
    if index >=5:
        index = 0
        break

but when I try both, it just inserts the value as many times as values in the list in the same index:

[1, 'k', 'k', 'k', 'k', 'k', 2, 3, 4, 5]

What am I missing?

Thanks in advance.

Solution:

What I would do is:

l = data
l2 = []
for i in data:
    l2.append(i)
    l2.append("k")

What is happening in your code:

you start by inserting k at index 1

[1, index 1 , 2, 3, 4] => [1, k, 2, 3, 4]

Then if you insert at index 2,

[1, k, index 2 , 2, 3, 4] => [1,k,k,2,3,4]

etc.

Also as a side note, on a large dataset insert would have to move all the items following in the list, so it would be very slow. My solution eliminates that, but creates a copy of the list.

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