0

If I have

list1 = [1, 2, 3, 6]
list2 = [4, 3, 5, 6]

how can I change the values of anything that matches between the two list? Only if the Index also matches

the desired output is

list1 = [1, 2, 3, 'match']

I was using this

for idx,x in enumerate(list1):
    if x in list2:  
        list1[idx] = 'match'

But this replaces the 3 and the 6

Barfield
  • 87
  • 1
  • 7

1 Answers1

0

Your code does not work because you are re-assigning to the x variable, not changing it's content. If you want a for-loop you can try this:

for idx,x in enumerate(list1):
    if x in list2:  # Assuming you meant list2 here instead of list1
        list1[idx] = 'match'

alternatively, a more "pythonic" way (from the comments) is:

list1 = ["match" if i in list2 else i for i in list1]
orestisf
  • 1,396
  • 1
  • 15
  • 30
  • Well, being the first to answer with a typo in a non-working code is really not useful... Please take your time to read the question and test your code. – Thierry Lathuille Jul 08 '20 at 11:39
  • Sorry, I didn't notice the typo in the original code – orestisf Jul 08 '20 at 11:40
  • 2
    There still is a typo, and your code still doesn't work. – Thierry Lathuille Jul 08 '20 at 11:41
  • 3
    And then reposting the comment of someone else as your answer, doesn't add much. – Ronald Jul 08 '20 at 11:42
  • Adding comments in an answer, especially when it is a complimentary alternative, is not against the rules or frowned upon. See here: https://meta.stackoverflow.com/questions/304126/is-it-correct-to-answer-copying-from-comments-by-other-users – orestisf Jul 08 '20 at 11:46