-1

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

  • https://stackoverflow.com/questions/53542860/in-python-how-is-the-in-operator-implemented-to-work-does-it-use-the-next-me – Avinash Apr 30 '22 at 12:09
  • It isn't printing anything in the first place. If the array is empty then the for loop won't initialize, since there is nothing to iterate over. – March_G Apr 30 '22 at 12:10
  • Why do you think it should raise an error? The standard inifinite loop is such that: `while True:` or `while 1:` – S3DEV Apr 30 '22 at 12:15

3 Answers3

1

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)
                
Avinash
  • 875
  • 6
  • 20
0

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

Anand Sowmithiran
  • 2,591
  • 2
  • 10
  • 22
0

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

Kamesh Kotwani
  • 104
  • 1
  • 7