Yasmin
Yasmin

Reputation: 951

How to create list of collections.Counter?

I have a for loop and each time I call a function within each iteration, and the return of that functions is from type " collections.Counter ", and I would like at the end of the loop that lst will contain all collection.Counter

for gram in range(0, nGram):
   lst[gram]=getCollection(gram)

Upvotes: 1

Views: 581

Answers (3)

Abhijit
Abhijit

Reputation: 63737

You can use the append method of the list as others have suggested or simply use list comprehension here

lst = [getCollection(gram) for gram in range(nGram)]

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1122062

For a list, you need to use .append():

for gram in range(nGram):
   lst.append(getCollection(gram))

You can turn that into a list comprehension:

lst = [getCollection(gram) for gram in range(nGram)]

Upvotes: 3

poke
poke

Reputation: 387687

Try to append it:

lst.append(getCollection(gram))

Otherwise (if gram is not a valid index of the list) you will end up with an IndexError, telling you that the list does not have that many elements—yet.

Upvotes: 1

Related Questions