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
#1
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.
Reply
#2
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
Reply
#3
This could be a fun little list comprehension. Use zip to pull the two lists together.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to parse and group hierarchical list items from an unindented string in Python? ann23fr 0 177 Mar-27-2024, 01:16 PM
Last Post: ann23fr
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,318 May-22-2023, 10:39 PM
Last Post: ICanIBB
Thumbs Down I hate "List index out of range" Melen 20 3,298 May-14-2023, 06:43 AM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 912 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Finding combinations of list of items (30 or so) LynnS 1 867 Jan-25-2023, 02:57 PM
Last Post: deanhystad
  user input values into list of lists tauros73 3 1,063 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  returning a List of Lists nafshar 3 1,056 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,610 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  Replace for loop to search index position illmattic 5 1,269 Sep-03-2022, 04:04 PM
Last Post: illmattic
  IndexError: list index out of range dolac 4 1,897 Jul-25-2022, 03:42 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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