Ivan
Ivan

Reputation: 1727

Trying to Write For-While Loop, not working

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

Upvotes: 2

Views: 84

Answers (3)

bkhouri
bkhouri

Reputation: 243

As an alternative to other answers, you can alternatively use list comprehension to achieve the results you are looking for:

list1  = ['a','b', 'c']
number = 5
list2  = [ '%s%s' % (item, i+1) for item in list for i in range(0,number) ]
print list2

Produces

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

Upvotes: 1

kundan
kundan

Reputation: 1288

Try this:

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

print list2

Output:

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

The code you shared, requires the following edit:

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

print list2

Upvotes: 0

devnull
devnull

Reputation: 123448

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

Upvotes: 1

Related Questions