Home > Software design >  How to iterate the range of numbers in a list?
How to iterate the range of numbers in a list?

Time:12-05

So this may sound like a dumb question and maybe I'm overthinking this, but I'm struggling to figure out how to iterate the range of numbers in a list. Say I have a list of numbers [100, 500, 1000]. I don't necessarily want to iterate through this list, but I want to iterate through the values if that makes sense. So I'm guessing I would iterate through the list first, but then I would need to create another loop for the values?

   for i in mylist:
        for j in range(0, mylist[i]):
             do something

I feel like this may be inefficient but would this be the way to do that?

CodePudding user response:

you are already fetching value from mylist in the first for loop. After than in the range you can just put that value directly (ie in second for loop) as shown below.

mylist = [100, 500, 1000]

for i in mylist:
    for j in range(0, i):
             print(j)

CodePudding user response:

If you have a list of numbers and you want to add up all the numbers and use that as the number of loops, you can do:

for i in range(sum(mylist)):
  #do_something
  • Related