Tom Kealy
Tom Kealy

Reputation: 2669

Enumerating namedtuples

I'm trying to create a list of namedtuples of the following form

from collections import namedtuple
item = namedtuple('item', 'position state')

I'd like to create the list so that the position field the item corresponds to the position of the item in the list.

So far I've tried:

l = [item(position=i, state=0)]*10

However this produces 10 items which look like this:

item(position=(0, item(position=0, state=0))

Could someone explain what's going on, and if there's a nice (one-line maybe) way of doing what I want.

Upvotes: 1

Views: 207

Answers (2)

Glabsounet
Glabsounet

Reputation: 557

This should work (too slow - kudos to NPE :p):

l = [item(position=i, state=0) for i in range(10)]

Upvotes: 3

NPE
NPE

Reputation: 500377

Yes:

l = [item(i, 0) for i in range(10)]

Upvotes: 3

Related Questions