How to get only lowercase strings from a list using list comprehension

  • A+
Category:Languages

The question asked:

Use list comprehensions to generate a list with only the lowercase letters in my_list. Print the result list.

['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D'] 

My code:

my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D'] hi = ([ char for char in range(len(my_list)) if char%2 == 0])  print(hi) 

I tried it out, but got integers as answers and not the strings I wanted.

 


Python strings have islower method. Also, you can directly iterate over the list, no need to check its length or the parity of the indexes.

my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D'] hi = [char for char in my_list if char.islower()] print(hi) # ['a', 'b', 'c', d'] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: