Sahil Deshpande
Sahil Deshpande

Reputation: 1

How to increment a value inside a list in python?

I have a list called quan = [0, 0 ,0, 0]. I'm asking the user to input integers between 0 to 3 and storing them in another list called items. eg: items = [0, 1, 1, 2, 2, 2]. For each int in items, I want to increment the corresponding position in quan, i.e., quan should become [1, 2, 3, 0] in this case.

for i in items:
    quan[items[i]] += 1

so far all I've ended up with an EoL error. A nudge in the right direction would be appreciated. Thanks.

Upvotes: 0

Views: 1275

Answers (3)

Hetal Thaker
Hetal Thaker

Reputation: 717

Below code loop will iterate only 4 times rather than no. of elements in items' list. count() of the list will return no. of occurrences of that element.

quan = [0, 0, 0, 0]
items = [0, 1, 1, 2, 2, 2]


for i in range(4):
    quan[i] += items.count(i)

print(quan)

or alternatively

quan = [quan[i]+items.count(i) for i in range(4)]

Upvotes: 1

nushen
nushen

Reputation: 61

The correct code is:

for i in items:
    quan[i]+=1

The EOL might be caused by a typo somewhere in the code.

Upvotes: 1

Jiří Baum
Jiří Baum

Reputation: 6940

For the question as asked:

quan = [0, 0, 0, 0]
items = [0, 1, 1, 2, 2, 2]

for i in items:
    quan[i] += 1

In most real situations, though, you probably want to use collections.Counter instead, which provides the same answer in slightly different form:

from collections import Counter

items = [0, 1, 1, 2, 2, 2]
quan = Counter(items)

Upvotes: 2

Related Questions