Python Forum
Create new list from another list based on condition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create new list from another list based on condition
#1
Hello
I have two lists X and Y as follows:

X = ['A','B','C','D','E']
Y = [ 1 , 0 , 1 , 1 , 0 ]
Here I need to create a new list Z that contains elements from X if the corresponding value in Y = 1.
So Z should be equals:
Z = ['A','C','D']

I tried the following code but it is not giving the proper output

Z = [X[i] for i in Y if Y[i] == 1]
but the result is not correct.

How to create the Z list using list comprehension ?
Reply
#2
one way:
X = ['A','B','C','D','E']
Y = [ 1 , 0 , 1 , 1 , 0 ]

spam = [x for x, y in zip(X, Y) if y]
print(spam)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 430 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Create dual folder on different path/drive based on the date agmoraojr 2 432 Jan-21-2024, 10:02 AM
Last Post: snippsat
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,161 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,513 May-01-2023, 09:06 PM
Last Post: deanhystad
  Sent email based on if condition stewietopg 1 858 Mar-15-2023, 08:54 AM
Last Post: menator01
  List all possibilities of a nested-list by flattened lists sparkt 1 915 Feb-23-2023, 02:21 PM
Last Post: sparkt
  create new column based on condition arvin 12 2,230 Dec-13-2022, 04:53 PM
Last Post: jefsummers
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,833 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,508 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 828 Sep-08-2022, 06:32 AM
Last Post: klllmmm

Forum Jump:

User Panel Messages

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