0

I try to increment a list at each iteration of a loop :

ads = []
page = {}
page['titre'] = "Title here"
page['nombre_pages'] = 396

i = 1 
total = 3

while i <= total:
    print(i)
    page['id'] = i
    ads.append(page)
    i += 1 

this return

[{'titre': 'Title here', 'nombre_pages': 396, 'id': 3}, {'titre': 'Title here', 'nombre_pages': 396, 'id': 3}, {'titre': 'Title here', 'nombre_pages': 396, 'id': 3}]

I don't understand why the same id 3 times and not id:1, id:2, id:3

When print page['id'] is ok (increment), ads.append(page['id']) is available too.

Can you help ?

Thanks

ChaosPredictor
  • 3,777
  • 1
  • 36
  • 46
Anthony Hervy
  • 1,201
  • 2
  • 7
  • 14

1 Answers1

1

you're only creating a single "page" object, i.e. by doing:

page = {}

and referring to it from several index locations in ads. you probably want to be doing something closer to:

ads = []

i = 1 
total = 3

while i <= total:
    print(i)
    page = {}
    page['titre'] = "Title here"
    page['nombre_pages'] = 396
    page['id'] = i
    ads.append(page)
    i += 1 

or slightly more idiomatically:

ads = []
total = 3
for i in range(total):
    ads.append({
        'nombre_pages': 396,
        'titre': "Title here",
        'id': i,
    })
Sam Mason
  • 15,216
  • 1
  • 41
  • 60