Intellipaat Back

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

I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.

for tup in somelist: 

      if determine(tup):

          code_to_remove_tup

What should I use in place of code_to_remove_tup? I can't figure out how to remove the item in this fashion.

1 Answer

0 votes
by (106k points)

You can remove the items that you want by using list comprehension and below is the example of list comprehension:

somelist = [x for x in somelist if not determine(x)]

Or, Another thing can be done is by using the slicing method, you can mutate(change in form) the existing list to contain only the items you want. This approach could be useful if there are other references to somelist that need to reflect the changes.

somelist[:] = [x for x in somelist if not determine(x)]

If you want other ways to solve this problem you can use the itertools module:-

itertools:-

The itertool module standardizes a core set of fast memory efficient tools that are useful by themselves in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.

An example that illustrates the use of itertools:-

from itertools import filterfalse 

somelist[:] = filterfalse(determine, somelist)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 8, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...