Skip to content
Advertisement

How to iterate over a list once only in a nested loop in Python

I intend to send message to many numbers, but this is my code and issue (code is made shorter and required lines are here):

msg = 'test message'
phone_numbers = ['+989111111111', '+989111111112', '+989111111113', '+989111111114']
hours = range(0, 25)
minutes = range(0, 60)
for phone_number in phone_numbers:
    for hour in hours:
        for minute in minutes:
            sndmsg(phone_number, msg, hour, minute)

I know my way is incorrect, because this is the output but I’m not sure how to solve this. Googling this did not help me.

Output:

test message to +989111111111 will be sent on 0 0
test message to +989111111111 will be sent on 0 1
test message to +989111111111 will be sent on 0 2
...
test message to +989111111112 will be sent on 0 0
test message to +989111111112 will be sent on 0 1
test message to +989111111112 will be sent on 0 2

My desired output would be like:

test message to +989111111111 will be sent on 0 0
test message to +989111111112 will be sent on 0 1
test message to +989111111113 will be sent on 0 3

I want to send the message to each number in each minute like the above output, how may I reach this?

Advertisement

Answer

Try using a generator for the hours and minutes and zip with the phone number:

msg = 'test message'
phone_numbers = ['+989111111111', '+989111111112', '+989111111113', '+989111111114']

def gen_hour_min():
    hours = range(0, 25)
    for hour in hours:
        minutes = range(0, 60)
        for minute in minutes:
            yield hour, minute

for phone_number, hour_min in zip(phone_numbers, gen_hour_min()):
    hour, minute = hour_min
    print(phone_number, hour, minute)
Advertisement