Python - Removing tuples by prefix and suffix from list
Python - Removing tuples by prefix and suffix from list
What's the fastest way to remove tuples from a python list (and update the list with the removed tuples) according to what the tuple starts with or ends with.
Example:
import itertools
l1 = ["a", "b", "c"]
l2 = ["d", "e", "f"]
tupl_lst = list(itertools.product(l1, l2))
tupl_lst
Out[42]:
[('a', 'd'),
('a', 'e'),
('a', 'f'),
('b', 'd'),
('b', 'e'),
('b', 'f'),
('c', 'd'),
('c', 'e'),
('c', 'f')]
I want to remove all tuples that starts with 'a'
OR ends with 'f'
so that my output will look as follows:
'a'
'f'
[('b', 'd'),
('b', 'e'),
('c', 'd'),
('c', 'e')]
What is the fastest way to do it ?
3 Answers
3
with a list comprehension:
[t for t in tupl_lst if t[0]!='a' and t[1]!='f']
with filter
:
filter
list(filter(lambda t: t[0]!='a' and t[1]!='f',tupl_lst))
You can even skip the itertools.product()
and just use one list-comprehension:
itertools.product()
l1 = ["a", "b", "c"]
l2 = ["d", "e", "f"]
tupl_lst = [(x, y) for x in l1 for y in l2 if x!="a" and y!="f"]
#output
[('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e')]
Avoid the prefix (a
) and suffix (f
) altogether by iterating over slices of the lists.
a
f
[(x, y) for x in l1[1:] for y in l2[:-1]]
# [('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e')]
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
%timeit list(filter(lambda t: t[0]!='a' and t[1]!='f',tupl_lst)) 1.3 µs ± 10.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) %timeit [t for t in tupl_lst if t[0]!='a' and t[1]!='f'] 665 ns ± 15.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) looks like the simple list comprehension is faster
– Eran Moshe
Aug 26 at 9:14