-3

I'm a newbie in the Python world. I'm still struggling with some of the basic concepts of Python.

Question: **Write a program that counts the number of string from a given list of strings. This string is 2 characters or more and the first and last characters are the same **

As the question mentioned in the title, this was my approach:

def string_num(items): 
    for a in items: 
        len(a) >= 3 and (a[0] == a[-1]) 
    return items.count(a) 
print(string_num(['abc','xyz','aba','1221'])) 

I assumed that the .count() function cannot be used here to count string in a list under a specific condition. I have been looking around but I still have not seen any explanation. Could someone help me explain what's wrong with this code, or what the .count() function does exactly that it cannot be used here?

Appreciate all the help!

Ch3steR
  • 20,090
  • 4
  • 28
  • 58

2 Answers2

0

Your mental model seems to be pretty far off from how Python actually works.

The for loop simply loops over an expression which ... does nothing. (It produces True or False in each iteration, but you don't do anything with that value.)

Finally, items.count(a) counts how many times a (which will be the value of a from the last iteration in the loop, which is still available after the loop has finished, i.e. '1221') occurs in items.

I guess you were looking for something like

def string_num(items): 
    return len([a for a in items if len(a) >= 3 and a[0] == a[-1]])

which can be written less succinctly as

def string_num(items): 
    count = 0
    for a in items:
        if len(a) >= 3 and a[0] == a[-1]:
            count += 1
    return count

As remarked by Unmitigated, you could even use sum here, since True is numerically equal to 1 and False is 0.

def string_num(items): 
    return sum(len(a) >= 3 and a[0] == a[-1] for a in items)
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 2
    It's not necessary to create a list to count the matching items: `return sum(len(a) >= 3 and a[0] == a[-1] for a in items)` – Unmitigated Mar 20 '23 at 15:56
0

The .count() function counts the occurences of a value in an array, see the example here. If you want to get the number of elements in a list, use the len() function you already used for the string length.

Also, this will not work, since you don't actually count the number of strings that fulfill this condition.

I would do something like this:

def string_num(items):
    item_count = 0
    for a in items: 
        if len(a) >= 3 and a[0] == a[-1]:
            item_count += 1
 
    return item_count
 
print(string_num(['abc','xyz','aba','1221'])) 

Or you could do it with list comprehension like this, which is a bit more concise:

def string_num(items):
    return len([v for v in items if len(v) >= 3 and v[0] == v[-1]])

print(string_num(['abc','xyz','aba','1221']))
ioasjfopas
  • 149
  • 5