Avión
Avión

Reputation: 8386

Iterating and printing a list in the wrong way

Having the following two list:

sist = ["item1", "item2", "item3"]
numbers = [2,1,4]

I want to print the elements of sist the number of times of the same index of numbers.

This means that in the example posted my desired output is:

item1
item1
item2
item3
item3
item3
item3

This is what I've tried with no success:

for idx in xrange(len(sist)):
    for num in numbers:
        i = 0
        print num
        while i < num:
            print sist[idx]
            i = i + 1 

I think I'm iterating in the wrong way as I'm getting this output:

2
item1
item1
1
item1
4
item1
item1
item1
item1
2
item2
item2
1
item2
4
item2
item2
item2
item2
2
item3
item3
1
item3
4
item3
item3
item3
item3

Can someone please tell me what I'm doing wrong and how to fix it?

Upvotes: 2

Views: 240

Answers (5)

SirParselot
SirParselot

Reputation: 2700

sist = ["item1", "item2", "item3"]
numbers = [2,1,4]

for i in range(len(numbers)):
    for j in numbers[i]:
        print(sist[i])
    print('')

I think this is the desired output you are looking for. It iterates over the numbers array and uses each element as the range for the second for loop. since numbers and sist are the same length you can just use i as the index for sist

Upvotes: 4

Will Vousden
Will Vousden

Reputation: 33348

To complement other answers, you can avoid nested loops like so:

from __future__ import print_function # This isn't needed in Python 3.

for n, item in zip(numbers, sist):
    print([item] * n, sep='\n')

Upvotes: 3

Anand S Kumar
Anand S Kumar

Reputation: 90889

You can use zip function to join the two lists at their corresponding indexes, and then print the first element (from sist) the number of times as the second element (from numbers)

sist = ["item1", "item2", "item3"]
numbers = [2,1,4]
for x, y in zip(sist, numbers):
    for _ in range(y):
        print(x)

The output is -

item1
item1
item2
item3
item3
item3
item3

Upvotes: 5

Blair
Blair

Reputation: 6693

This calls for a nested for loop, like the following:

>>> sist = ["item1", "item2", "item3"]
>>> numbers = [2,1,4]
>>> for i in xrange(len(numbers)):
    for j in xrange(numbers[i]):
        print sist[i]


item1
item1
item2
item3
item3
item3
item3

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117856

If you would like to use nested for loops like this, you could do

for item, rep in zip(sist, numbers):
    for _ in range(rep):
        print(item)

Output

item1
item1
item2
item3
item3
item3
item3

Upvotes: 5

Related Questions