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))





%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




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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)