Python Forum
Compare Two Lists and Replace Items In a List by Index - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Compare Two Lists and Replace Items In a List by Index (/thread-26691.html)



Compare Two Lists and Replace Items In a List by Index - nagymusic - May-09-2020

I'm working on a problem in which I'd like to compare two lists of numbers:

list_a = [0, 1, 2, 3]
list_b = [4, -2, 3, -1]
Then, I'd like to create a new list_c that transforms the list_a by examining every negative number in list_b and then replaces the corresponding number in list_a (at the same index number when compared to list_b) with None.

list_c = [0, None, 2, None]
I welcome your suggestions on what would be the most efficient way to achieve this. Thank you.


RE: Compare Two Lists and Replace Items In a List by Index - SheeppOSU - May-09-2020

The best option here is a for loop. For loops are used to loop through a list or through something with a set number of loops. We have a set number of loops here which is the list, so a for loop would work best. I'd rather that you solve this yourself so I'll explain to you how you can implement this. First you need to create the list_c. Next, you should loops through list_b since that's the one you're checking for negative numbers. If you loop through the elements in list_b you would have to create an index variable yourself which is extra code, so to make it more efficient I suggest the following: for index in range(0, len(list_b)), then the elements from list_a and list_b can be accessed using list_a[index] and list_b[index]. So the code inside the for loop should look to see if the element of list_b is a negative number, if it isn't then do nothing, otherwise: list_a[index] = None.
Hope this help


RE: Compare Two Lists and Replace Items In a List by Index - deanhystad - May-10-2020

This could be a fun little list comprehension. Use zip to pull the two lists together.