Reputation: 558
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
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
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
Reputation: 19733
Pythonic way: list comprehension
>>> [{'id':x} for x in range(4)]
[{'id': 0}, {'id': 1}, {'id': 2}, {'id': 3}]
Upvotes: 4