Fartash
Fartash

Reputation: 558

How get the value of counter in python for loop

What is the best way to fix the following code

my_list=[]
elem={}
for i in range(4):
    elem['id']=i
    my_list.append(elem)
print my_list

result

[{'id': 3}, {'id': 3}, {'id': 3}, {'id': 3}]

expected result

[{'id': 0}, {'id': 1}, {'id': 2}, {'id': 3}]

**I don't want to use another variable

Upvotes: 0

Views: 101

Answers (3)

Shashank
Shashank

Reputation: 13869

my_list = []
for i in range(4):
    mylist.append({'id': i})

This is practically equivalent to:

my_list = [{'id': i} for i in range(4)]

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174706

You need to empty the dictionary inside the for loop itself.

my_list=[]
elem={}
for i in range(4):
    elem['id']=i
    my_list.append(elem)
    elem={}
print my_list

Output:

[{'id': 0}, {'id': 1}, {'id': 2}, {'id': 3}]

OR

simply,

my_list=[]
for i in range(4):
    elem = {}
    elem['id']=i
    my_list.append(elem)

print my_list

Upvotes: 4

Hackaholic
Hackaholic

Reputation: 19733

Pythonic way: list comprehension

>>> [{'id':x} for x in range(4)]
[{'id': 0}, {'id': 1}, {'id': 2}, {'id': 3}]

Upvotes: 4

Related Questions