Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using list comprehension instead of function

Tags:

python

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])
like image 748
Madrid_datalady Avatar asked Apr 30 '26 16:04

Madrid_datalady


1 Answers

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.

like image 153
jpp Avatar answered May 03 '26 06:05

jpp