Eugene Brown
Eugene Brown

Reputation: 4362

How do I access each element in list in for-loop operations?

I am looping through this list and don't understand why print(d) returns each number in seed but assigning i["seed"] = d assigns the last element of seed.

How do I access each element in seed for operations other than print()?

res = []
seed = [1, 2, 3, 4, 5, 6, 7, 8, 9]
i = {}
for d in seed:
    print(d)
    i["seed"] = d
    res.append(i)
print(res)

Thanks!

Upvotes: 3

Views: 905

Answers (4)

Corgs
Corgs

Reputation: 342

To answer your first question, it is because thew value of seed is being overwritten, as shown here:

>>> p = {'t':'H'}
>>> p['t'] = 'k'
>>> p
{'t': 'k'}

Upvotes: 0

Logan McCaul
Logan McCaul

Reputation: 36

Curly braces {} in python represent dictionaries which works based on a key and value. Each time you iterate through your loop you overwrite the key: 'seed' with the current value of the list seed. So by the time the loop ends the last value of the list seed is the current value of seed in the dictionary i.

Upvotes: 0

meganaut
meganaut

Reputation: 503

The problem is where you are defining i. I think you intended to have a dictionary object named i that has single attribute named "seed". and you want to add those dictionaries to res.

In actual fact you only have one dictionary called i and you just update the value in it every time through the loop.

try this:

res = []
seed = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for d in seed:
    i = {}
    print(d)
    i["seed"] = d
    res.append(i)
print(res)

That will create a new instance of i for each loop, and you should get the result you are looking for.

Upvotes: 2

Gerrat
Gerrat

Reputation: 29690

The issue is there is only one object i, and you're replacing its value every time in the loop. By the last iteration your (one instance) of i has its value set to the last item you assigned it to. Each time you append to res, you're basically appending the a pointer to the same object (so you end up with 9 pointers pointing to the same object when your loop is finished).

res = []
seed = [1, 2, 3, 4, 5, 6, 7, 8, 9]
i = {}
for d in seed:
    print(d)
    i["seed"] = d  # this gets replaced every time through your loop!
    res.append(i.copy())  # need to copy `i`, or else we're updating the same instance
print(res)

Upvotes: 0

Related Questions