0

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?

1
  • This is not a typical use for a while loop. While you can make it work, I would highly suggest one of the other solutions posted below not using while. Commented Aug 31, 2020 at 13:10

4 Answers 4

4

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)]
Sign up to request clarification or add additional context in comments.

Comments

2

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)]

Comments

1

You can do it in pythonic way:

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

Comments

0

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)

1 Comment

Your answer would be better if you added an explanation. Use edit to annotate the answer.

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.