Python Forum
Compare Two Lists and Replace Items In a List by Index
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Compare Two Lists and Replace Items In a List by Index
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.
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
This could be a fun little list comprehension. Use zip to pull the two lists together.

Possibly Related Threads…
Thread Author Replies Views Last Post
  Creating list of lists from generator object t4keheart 1 121 Nov-13-2020, 04:59 AM
Last Post: perfringo
  How to get index of minimum element between 3 & 8 in list Mekala 2 152 Nov-10-2020, 12:56 PM
Last Post: DeaD_EyE
  Count number of occurrences of list items in list of tuples t4keheart 1 106 Nov-03-2020, 05:37 AM
Last Post: deanhystad
  How do i make a new lists out of an list ozezn1 1 159 Oct-28-2020, 10:19 PM
Last Post: Gribouillis
  concatenating 2 items at a time in a python list K11 3 161 Oct-21-2020, 09:34 AM
Last Post: buran
  List index out of range error while accessing 2 lists in python K11 2 256 Sep-29-2020, 05:24 AM
Last Post: K11
  Comparing items from 2 lists of dictionaries illwill 7 242 Sep-14-2020, 10:46 PM
Last Post: bowlofred
  Select the other of 2 items in a list Clunk_Head 7 448 Sep-01-2020, 05:27 PM
Last Post: Clunk_Head
  Removing items from list if containing a substring pythonnewbie138 2 351 Aug-27-2020, 10:20 PM
Last Post: pythonnewbie138
  list indices must be integers or slices, not lists error djwilson0495 2 345 Aug-27-2020, 06:13 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020