简体   繁体   中英

How does a loop in a loop work with python

For example I have the below code:

websites = ['<html><head></head><body></body></hmtl>']
emails = []

for sourcecode in websites:
    #Search the link before writing
    x = re.findall(r'(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b', sourcecode)
    for email in x:
        emails.append(email)


print(emails)
print(len(emails))

The websites is an array of source code from many different websites. The emails array is empty becuase we will be looping through the websites source code and looking for email addresses and than appending them into the emails array. Essentially extracting email addresses. Then printing the emails and printing the amount of emails extracted.

The above code is working. However lets say I have 5 source codes. How does it function with a loop in a loop.

I assume the first loop runs and starts from 0 index in the array. Then proceeds to the next loop to extract all the emails. The second loops would loop through all the arrays essentially completing its task. Then the first loop would proceed to 1 index in the array and then the second loops would loop through the whole index of that array completing its task and the cycle would continue until the first loop finishes.

It this how it executes or could someone please shed more light. Thanks! :)

The inner loop will perform all of its iterations for each iteration of the outer loop.

This is a case where you can test the behaviour yourself fairly easily, and generally it is faster to try these kinds of things out than to ask the question on here and wait for an answer.

For example, given the following code:

for i in range(3):
    print(i)
    for x in ['a', 'b', 'c']:
        print(f' - {x}')

you get the following output:

0
 - a
 - b
 - c
1
 - a
 - b
 - c
2
 - a
 - b
 - c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM