Reputation: 4014
I have the following list:
fruits = ['apple', 'cherry', 'banana', 'lemon']
And using a list comprehension, i need to generate a list that contains the fruits (in uppercase) that contain the letter 'a', so apple and banana.
I tried using:
small=[s.upper() for s in fruits for c in s if c=='a']
But it gives me a result with duplicates:
['APPLE', 'BANNANA', 'BANNANA', 'BANNANA']
How can i fix that? Thanks!
Upvotes: 0
Views: 586
Reputation: 8906
You have two for loops in there but you only need one. Also, you're checking only the first character for 'a', but from the text I understand that 'a' could appear anywhere in the input. Plus, while this is not the case in your example, I assume it should also work for input strings that are not all-lowercase (like 'Apple'), so you should lower()
the string before comparing with 'a'.
[s.upper() for s in fruits if 'a' in s.lower()]
Upvotes: 1
Reputation: 39069
[fruit.upper() for fruit in fruits if 'a' in fruit]
List comprehension can be a bit hard to comprehend. In this case it should be read from the middle out. You loop over all fruits (yeah, I know...), filter only those with 'a's in them and then convert them to upper case.
Upvotes: 0
Reputation: 9856
[s.upper() for s in fruits if 'a' in s]
The reason your list comprehension doesn't work is because it expands to this:
result = []
for s in fruits:
for c in s:
if c == 'a':
result.append(s.upper ())
This will go through every character in fruit
and keep all those fruits that have an 'a' in them, in proportion to how often 'a' appears in each fruit.
Upvotes: 4