Trying to write for while loop, does not work

advertisements

This is my first question, so I am sorry if it needs retitling or moving to another section.

I am trying to write a loop that will append numbers 1-4 to every string in list1 and put those new strings in list2. Here is what I'm doing so far:

number = 0
list1 = ["a","b","c"]
list2=[]
for item in list1:
    while number < 5:
        list2.append(str(item)+str(number))
        number = number + 1

I am lost on what to do next. Any help would be appreciated.

P.S. Right now, if i do print list2 it outputs ['a0', 'a1', 'a2', 'a3', 'a4']. What I want to happen is

print list2

['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4']


The problem is that you have initialized number outside the for loop. As such, even though the for is executed for all items in list1, the while isn't executed for subsequent items as the condition is false.

list1 = ["a","b","c"]
list2=[]
for item in list1:
    number = 1       # You need to reset number within the loop, not outside!
    while number < 5:
        list2.append(str(item)+str(number))
        number = number + 1
print list2

Produces:

['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4']