3

This question is similar to Check that list of tuples has tuple with 1st element as defined string but no one has properly answered the "wildcard" question.

Say I have [('A', 2), ('A', 1), ('B', 0.2)]

And I want to identify the tuples where the FIRST element is A. How do I return just the following?

[('A', 2), ('A', 1)]

3 Answers 3

6

Using a list comprehension:

>>> l = [('A', 2), ('A', 1), ('B', 0.2)]
>>> print([el for el in l if el[0] == 'A'])
[('A', 2), ('A', 1)]
0
3

You could use Python's filter function for this as follows:

l = [('A', 2), ('A', 1), ('B', 0.2)]
print filter(lambda x: x[0] == 'A', l)

Giving:

[('A', 2), ('A', 1)]
1
  • Great use of filter and the lambda function. Thank you! And thank you for adding the link to the other question! I will do that in the future...(rookie mistake).
    – amc
    Commented Feb 22, 2016 at 17:44
3

Simple enough list comprehension:

>>> L = [('A', 2), ('A', 1), ('B', 0.2)]
>>> [(x,y) for (x,y) in L if x == 'A']
[('A', 2), ('A', 1)]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.