Madrid_datalady
Madrid_datalady

Reputation: 79

Using list comprehension instead of function

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])

Upvotes: 3

Views: 246

Answers (4)

U13-Forward
U13-Forward

Reputation: 71570

Or len+filter:

>>> li=['abc', 'xyz', 'aba', '1221']
>>> len(list(filter(lambda x: len(x)>1 and x[0]==x[-1],li)))
2
>>> 

list.count is incapable of counting by condition nor multiple items, only one single value.

To explain mine:

  • Make a filter object conditioning it being bigger than 1 and first element is the same as last element

  • Make the filter object a list

  • Then get the length of it.

Upvotes: 1

JRehl
JRehl

Reputation: 19

Try this:

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

It is very similar to your original answer, except

  • remember to put [] around your list comprehension
  • li.count(item) will count how many times the item occurs in the list. But actually you want how many items are in the list, so use len(list).
  • Upvotes: 2

    jpp
    jpp

    Reputation: 164653

    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.

    Upvotes: 6

    blhsing
    blhsing

    Reputation: 106533

    You can use sum with a generator expression instead:

    sum(1 for x in li if len(x)>1 and x[0] == x[-1])
    

    Upvotes: 2

    Related Questions