0
votes

I'm trying to teach myself list comprehension in Python, but I find it quite tricky compared to regular loops and it is hard to find good beginner examples of list comprehension.

Using this basic example below, it supplies a list of numbers and asks for sentences generated such as "2 numbers start with 1."

my_list = [232, 379, 985, 384, 129, 197]
2 numbers start with 1
1 number starts with 2
2 numbers start with 3
1 number starts with 9

If I was going to do this in a loop, I might bring back the first digit in each like this and then count them and put them in print statements (this just shows how I might start out in a loop):

for x in range(len(my_list)):
    strList = (str(my_list[x]))
    if strList[0]:
        print(strList[0])

I'm so confused about how to bring back element [0] in list comprehension. I know there is a sum available in list comprehension, so I'm trying to start like this below to create a count (this isn't right though) and I don't know how to retrieve the first elements back out of this so I can piece together sentences like "2 numbers start with 1":

count = [sum(x) for x in my_list if my_list[0]]

print(count,' numbers start with', start_digit)

Thanks for any help with understanding list comprehension. It looks much better than loops in terms of being more concise so I want to learn it.

1

1 Answers

1
votes

Perhaps the reason why you're getting confused here is that this particular problem doesn't seem like something that list comprehension would solve.

If you only need to get the first digits of the items, then list comprehension can do the trick:

start_digits = [str(x)[0] for x in my_list]

Getting the occurrences of each item is a completely different story. You can it implement in a variety of ways, and if you're not against importing modules, you can use collections.Counter to get the occurrence counts.

from collections import Counter
Counter(start_digits)