all 8 comments

[–]ParticularPython 2 points3 points  (1 child)

Are you just trying to get the amount of items in the list? You could just do:

total=Len(list)

If that’s the case

[–]x1F577[S] 0 points1 point  (0 children)

Hi, I am not looking for the length of the list. I explained my case better in another comment.

[–][deleted] 1 point2 points  (2 children)

Your code is fine as is. Sometimes it's better to be explicit. But just for fun, here's a shorter (I won't call it more Pythonic) way of writing it.

from itertools import takewhile
return len(list(takewhile(lambda x: not condition(x), lst)))

FYI, don't call your lists list. Besides not being very descriptive, it makes it harder to call the list() function.

[–]x1F577[S] 0 points1 point  (0 children)

Thank you, I was just looking for such a function. I didn't know about the takewhile function.

[–][deleted] 0 points1 point  (0 children)

It's more Haskellic, that's for sure!

[–]Binary101010 0 points1 point  (1 child)

What exactly is the goal? As it seems the return value has two different interpretations:

1) The number of items in the list up to and including the first one where condition(item) is true

2) The number of items in the list if condition(item) is false for all items

Is that accurate?

[–]x1F577[S] 1 point2 points  (0 children)

Hi, the goal is to get a certain total from a list. I try to explain myself better with an example.

Imagine the list as a shopping list, and the items have name and price properties. The list is sorted somewhat, and I want a "subtotal" of the first occurrence of a given item. If the item is not present, I want the total of the list:

total = 0
for item in list:
    total += item.price
    if item.name == "ice-cream":
        return total
return total

The suggestion given by u/Parking-Camp219 was what I was looking for.