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
Age Doesn't Matter, Your Passion Does
- Shreya Jain
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
  behavior list of lists roym 5 240 Jul-04-2021, 04:43 PM
Last Post: roym
  IndexError: list index out of range Laplace12 1 260 Jun-22-2021, 10:47 AM
Last Post: Yoriz
  Feed List items with Integer euras 9 577 May-19-2021, 07:45 PM
Last Post: snippsat
  List of lists - merge sublists with common elements medatib531 1 517 May-09-2021, 07:49 AM
Last Post: Gribouillis
  Sort List of Lists by Column Nju 1 473 Apr-13-2021, 11:59 PM
Last Post: bowlofred
  Parse String between 2 Delimiters and add as single list items lastyle 5 614 Apr-11-2021, 11:03 PM
Last Post: lastyle
  IndexError: list index out of range brunolelli 11 1,161 Mar-25-2021, 11:36 PM
Last Post: brunolelli
  Changing Index of 2 List in python giddyhead 0 409 Mar-05-2021, 05:45 PM
Last Post: giddyhead
  Sum of list items tristanfermat 2 525 Feb-06-2021, 12:04 PM
Last Post: tristanfermat
  IndexError: list index out of range ramu4651 2 683 Jan-24-2021, 01:45 PM
Last Post: buran

Forum Jump:

User Panel Messages

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