-2

How do i write a list comprehension in python with an inclusion of a count = count + 1?

print sum([info[count]["count"] for i in info])

# This is the working loop: 

count = 0
lst = []
for i in info:
    num = info[count]["count"]
    # print num
    count = count + 1
    lst.append(num)
print sum(lst)
lavidar
  • 11
  • 1
  • 1
  • 3
    Use `enumerate`. There must be numerous examples on SO and in the python docs. – Paul Rooney Mar 02 '16 at 22:00
  • 4
    What is the point of `count`? Why not just use `i`?! – jonrsharpe Mar 02 '16 at 22:00
  • as suggested by @jonrsharpe, why don't you use `sum(i["count"] for i in info)`? – Julien Spronck Mar 02 '16 at 22:04
  • In my opinion, a related but better posed question is already answered [here](http://stackoverflow.com/questions/9197844/maintain-count-in-python-list-comprehension). One can probably extract what one needs from the answers provided to the linked page. – ximiki May 11 '17 at 15:53

2 Answers2

3
    >>> a = ['a','b','c']
    >>> v = ['a','e','i','o','u']
    >>> len(a)
    3
    >>> sum([1 for x in a if x in v])
    2
mcstafford
  • 31
  • 2
  • 2
    It is helpful to describe what is going on with your code. This will give context and help the OP as well as people that come across this answer in the future. – hcoat Jun 07 '18 at 01:50
  • For me the result is `1`, which is the expected result in my case. Not sure how the code above could give `2` as result given that only value 'a' is in collection `a` and collection `v`. – Bazzz May 19 '22 at 09:52
0

I do not follow why you use i in i in info together with count. If info is enumerable and enumerating has the same effect as accessing with a zero offset index (like you seem to do with count, you can rewrite your loop like:

lst = []
for infoi in info:
    num = infoi["count"]
    # print num
    lst.append(num)

print sum(lst)

Now you can convert this to the following list comprehension:

sum([infoi["count"] for infoi in info])

Finally you do not need to materialize the comprehension to a list, sum can work on a generator:

sum(infoi["count"] for infoi in info)

This can be more efficient, since you will not construct a list first with all the values: sum will enumerate over all items and thus will result in constant memory usage.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555