Search code examples
pythonlistfor-looplist-comprehension

How to replace list items in order of another list in Python


Let's take this list:

list2 = ['<@25032923629058>', 'dad', 'awd', '<@65432156029058>', '<@98450239029058>']

I would like to replace the elements that start with <@ in order of this list:

list = ['dd#1111', 'dd#2222', 'dd#333']

Expected result:

['dd#1111', 'dad', 'awd', 'dd#2222', 'dd#333']

The following script changes every item that starts with <@ with the same value, which i want to avoid:

for i in range(len(list2)):
    if list2[i].startswith("<@"):
        list2[i] = list[0]
print(list2)

Solution

  • A simple fix, delete list[0] after replacing it.

    for i in range(len(list2)):
        if list2[i].startswith("<@"):
            list2[i] = list[0]
            del list[0]
    print(list2)
    

    On a second note, don't name your lists as list. This is a bad practice that will hurt you in the long run.