Home > OS >  How python handle iteration in blank
How python handle iteration in blank

Time:04-30

Why python doesn't raise an error when I try do this, instead it print Nothing.

empty = []
for i in empty:
    for y in i:
        print(y)

Is that python stop iterate it the first level or it just iterates over and print None?

I found this when trying to create a infinite loop but it stop when list become empty

CodePudding user response:

Your list variable empty is initialized with empty list. so, the first iteration itself will not enter, since the list is empty.

CodePudding user response:

Since the list is empty, the loop will not run at all.

CodePudding user response:

There is nothing to iterate over in empty list. Hence, for loop won't run even for a single time. However, if it is required to get an error for this you can raise an exception like below:

empty = []
if len(empty) == 0:
    raise Exception("List is empty")
for i in empty:
    for y in i:
        print(y)
                
  • Related