3

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])
3
  • List comprehensions need to be in brackets: [x for x in li if len(x)>1 and x[0] == x[-1]] should work. Commented Nov 15, 2018 at 23:28
  • 4
    len([x for x in li if len(x) >= 2 and x[0] == x[-1]]) Commented Nov 15, 2018 at 23:28
  • Thanks CJ59. Indeed, I had forgotten to use square brackets, but even still the code you suggested didn´t work (it gives a result of 0). I think there´s an issue with the li.count, as jpp pointed out below. Commented Nov 15, 2018 at 23:40

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use sum with a generator expression instead:

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

Comments

2

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).
  • Comments

    1

    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.

    Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.