0

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

3 Answers 3

4

Pythonic way: list comprehension

>>> [{'id':x} for x in range(4)]
[{'id': 0}, {'id': 1}, {'id': 2}, {'id': 3}]
Sign up to request clarification or add additional context in comments.

Comments

4

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

4 Comments

for i in range(4): elem={} elem['id']=i my_list.append(elem) I think we don't need to declare elem={} twice.
We can also move elem={} as the first statement within the loop and get rid of the first one right before the loop.
@TanveerAlam elem is never declared twice during execution. It's just that the code can be shrunk down and be better structured.
@Tarik I just went through your profile Sir and I think you have typo error in about me section. You have mentioned Haslell which should be Haskell I think.
3
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)]

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.