Using list comprehension instead of function

  • A+
Category:Languages

I am trying to write a Python program that counts the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.

Sample List : ['abc', 'xyz', 'aba', '1221'] - expected answer is 2

I have the code using a function, but am curious to know whether there is a simpler way to write it by using list comprehension.

I wrote the following code but it doesn't work. Is it because the question is unsolvable with list comprehension or because I have gotten something wrong with the code?

li=['abc', 'xyz', 'aba', '1221'] li.count(x for x in li if len(x)>1 and x[0] == x[-1]) 

 


list.count counts occurrences of a given value in a list. More appropriate, you can use sum with a generator comprehension:

li = ['abc', 'xyz', 'aba', '1221']  res = sum((len(x) >= 2) and (x[0] == x[-1]) for x in li)  # 2 

This works because bool is a subclass of int, i.e. True == 1 and False == 0.

Comment

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