Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:

good = [x for x in mylist if x in goodvals] 

bad = [x for x in mylist if x not in goodvals]

is there a more elegant way to do this?

Update: here's the actual use case, to better explain what I'm trying to do:

# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ] 

IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png') 

images = [f for f in files if f[2].lower() in IMAGE_TYPES] 

anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]

1 Answer

0 votes
by (106k points)

To split a list based on a condition you can use the below-mentioned code:-

good, bad = [], [] 

for x in mylist:

(bad, good)[x in goodvals].append(x)

Related questions

0 votes
2 answers
asked Oct 3, 2019 in Python by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jan 5, 2021 in Python by laddulakshana (16.4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...