0

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.

2
  • 3
    just do quan[i] += 1. i contains the element, not the index so you can access it directly using quan[i]. Commented Feb 27, 2021 at 8:06
  • 1
    I don't see a reason for End of Line error. Commented Feb 27, 2021 at 8:12

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Counter does not maintain the right item order, so this is probably not a useful alternative.
Yeah; that's why I provided the "as asked" answer. In most real situations, though, either the item order is irrelevant or the Counter can be scanned in order; either way, using a library function is usually better than writing code.
The question goes "the user provides a list of positions to increment, and then I want to increment those positions", so the position of the element is kind of important. Counter does something entirely different. (Not to mention that quan is probably not always all zero at the start.)
1

The correct code is:

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

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

Comments

1

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.