AttributeError: 'list' object has no attribute 'replace',

Question:

testdeck = ['apple', 'banana', 'napalm', 'ice','rock','death','plush','rush']
finaldeck = [1,2,3,4,5,6,7,8]

for card in testdeck:
    index = testdeck.index(card)
    print('index',index,'card',card)
    
    for item in finaldeck:
        if type(item) == int:
            print(item,'integer','replacing...')
            finaldeck = finaldeck.replace(item,card)
        elif type(item) == str:
            print(item,'string'' not replacing...')


#example(end game)

exampledeck = ['banana','apple]
exmapledeck2 = [1,2,3,4]


exampledeck2 = ['banana','apple,3,4]

Finaldeck already has 8 items, each one being an integer
the idea is that every string in testdeck will need to be placed in the first integer found available in finaldeck.

Asked By: Br3xin

||

Answers:

You just need to use zip and enumerate together:

testdeck = ['apple', 'banana', 'napalm', 'ice','rock','death','plush','rush']
finaldeck = [1,2,3,4,5,6,7,8]

for index, (card, item) in enumerate(zip(testdeck, finaldeck)):
    if isinstance(item, int):
        finaldeck[index] = card

This is a single pass through both lists at the same time, terminating at the end of the shortest list.

Answered By: quamrana
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.