djangodjames
djangodjames

Reputation: 319

Problem with adding numbers to a string in a while loop Python

I need to generate a list of items with number. For example:

item-1
item-2
item-3
..
item 246234

I'm trying to solve it with a while loop. Here is my code:

pages = []
page = 'item-'
nr = 1
last = 10
while nr <= last
    page = page + str(nr)
    pages.append(page)
    nr += 1

But instead of desired result I got:

item-1
item-12
item-123
item-1234
and so on

How can I fix this problem?

Upvotes: 0

Views: 496

Answers (4)

PRANJAL
PRANJAL

Reputation: 1

Here is my way, loop till the last number of pages and append to list creating each page with the current index:

pages=[]
pagex = "item-"
for i in range(1,last+1):
    page = pagex + str(i)
    pages.append(page)

Upvotes: 0

Yaroslav Hladkyi
Yaroslav Hladkyi

Reputation: 335

You can do it in pythonic way:

pages = ['item-'+str(nr) for nr in range(1, last+1)]

Upvotes: 1

tobias_k
tobias_k

Reputation: 82949

Your page accumulates numbers in each iteration. Use another variable name inside the loop:

while nr <= last
    pageX = page + str(nr)
    pages.append(pageX)
    nr += 1

Or add the page directly to the list, with no intermediate variable:

while nr <= last:
    pages.append(page + str(nr))
    nr += 1

Or use a for loop so you don't have to check and increment the number yourself:

for nr in range(1, last+1):
    pages.append(page + str(nr))

Or a list comprehension to make the whole code shorter and (IMHO) more readable:

pages = ["item-" + str(nr) for nr in range(1, last+1)]

Upvotes: 4

tzaman
tzaman

Reputation: 47870

When you say page = ... you're overwriting the original "template" that you use every time. Just use a different variable:

while nr <= last:
    current_page = page + str(nr)
    pages.append(current_page)
    nr += 1

Incidentally, this is much more clearly expressed in idiomatic python as follows:

pages = [f"item-{i}" for i in range(1, 11)]

Upvotes: 2

Related Questions