Because otherwise without it, if you either refer to it in the loop, it won't exist so you'll get an error. Or if you define it in the loop, you'll redefine it every iteration, destroying all the progress added to it from every previous iteration. Answer from External-Ocelot206 on reddit.com
๐ŸŒ
Snap! Forum
forum.snap.berkeley.edu โ€บ bug reports โ€บ snap! bugs
Problem with for loop with list if list is empty - Snap! Bugs - Snap! Forum
October 2, 2021 - If you have it like this: [scratchblocks] for ((i) :: control) = (1) to ([length v] of (list) :: list) { ... } @loopArrow :: control [/scratchblocks] if the list is empty, it will evaluate ...
Top answer
1 of 3
4

The thing that I think you're missing here is that the StopIteration is what actually makes the for loop stop. This is why you can write custom iterators that work with Python's for loop transparently. It doesn't do any checking to see if the iterator is empty, and the for loop does not keep track of of the iterator's state. This is an effect of the iterator protocol, and was an intentional choice in the language design. You can read more about the iterator protocol on Python's docs site if you want to.

It also makes more sense if you think about the number of items in e.g. your list corresponding directly to the number of times your loop is executed.

-----------------------------------|
| No. of items | No. times executed|
------------------------------------
|      5       |         5         |
|      4       |         4         |
|      3       |         3         |
|      2       |         2         |
|      1       |         1         |
|      0       |         0         |
------------------------------------

If the for loop special-cased an empty iterable, this invariant would be lost.

It would also complicate the protocol on writing custom iterators, because you would have to have an extra method to signal to the for loop that your iterable is empty before the iteration began.

Here's a (stupid) example of a custom iterator that always acts like it's empty:

class EmptyIterator():
    def __iter__(self): return self
    def __next__(self): raise StopIteration

for blah in EmptyIterator():
    print('this is never reached')
try:
    next(EmptyIterator())
except StopIteration:
    print('Oh hi, I was empty so I raised this Exception for you.')
2 of 3
10

This is odd to me. Why should an empty collection be treated any differently?

Forcing the programmer to check if the collection is empty before doing things to it would be a widespread, problematic sort of burden. Worse, an empty collection is in no way exceptional.

Personally, I would rather have the occasional bug where a no-op happened because I forgot to check for the rare case where I wanted different behavior on an empty collection rather than the occasional bug where an exception crashes my app because I forgot to say if empty, do nothing everywhere I wanted that common, expected behavior.

I mean, do you think printing empty strings should throw exceptions?

๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-empty-list
A Comprehensive Guide to Python Empty Lists | DataCamp
February 2, 2024 - In situations where the amount or type of data is unpredictable, empty lists emerge as flexible containers for dynamically accumulating information. Consider a program that reads user input until a specific condition is met. Here, we donโ€™t know the number of user inputs we may get, and by using the .append() method, we are able to add elements to the list user_response dynamically. # Initialize an empty list to store user input user_responses = [] # Collect user input in a loop while True: response = input("Enter your response (or type 'exit' to finish): ") if response.lower() == 'exit': break user_responses.append(response) # User responses are now stored in `user_responses`
๐ŸŒ
Quora
quora.com โ€บ Is-there-a-way-in-which-an-empty-list-that-gets-filled-up-with-int-elements-during-a-loop-can-be-the-loop-variant
Is there a way in which an empty list that gets filled up with int elements during a loop can be the loop variant? - Quora
Answer (1 of 2): Due to the word โ€œemptyโ€ in the question, I think the answer is no. I think you intend something like: [code]mylist = [ ] for x in mylist: mylist.append(foo) if something: mylist.pop() [/code]The if and pop in statement #4 provides a way for the for loop to terminate eventua...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ add-values-into-an-empty-list-from-python-for-loop
Add Values into Empty List Using For Loop - Python - GeeksforGeeks
July 23, 2025 - Lists are versatile data structures that allow you to store and manipulate collections of items. The simplest way to add values to an empty list is by using append() method. This method adds a single item to the end of the list.
Find elsewhere
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-empty-list-tutorial-how-to-create-an-empty-list-in-python
Python Empty List Tutorial โ€“ How to Create an Empty List in Python
June 18, 2020 - In the example below, we create an empty list and assign it to the variable num. Then, using a for loop, we add a sequence of elements (integers) to the list that was initially empty:
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 35569956 โ€บ how-to-append-a-empty-list-within-for-loop-in-python
numpy - How to append a empty list within for loop in Python - Stack Overflow
a=np.where(MACD[2]>0.)[0] b=np.where(MACD[2]<0.)[0] num=np.array([1,2]) num1=[] for x in range (-1,-30,-1): while True: if(a[x]-a[x-1]>1): num1.append(num) print num1 break
๐ŸŒ
Developer Diary
varunver.wordpress.com โ€บ 2017 โ€บ 06 โ€บ 29 โ€บ python-iterate-over-a-list-and-check-if-its-not-empty
Python โ€“ Iterate over a list and check if itโ€™s not Empty
June 26, 2021 - When I used a list comprehension, it would fail if the list was None. But it would if the list was empty []. The old and easy way of doing this was: if tags: for t in tags: # Do stuff with t ยท The pythonic way of merging the if statement within the list comprehension is: for t in [t for t in (tags or [])]: # Do stuff with t ยท
๐ŸŒ
Codecademy Forums
discuss.codecademy.com โ€บ frequently asked questions โ€บ python faq
Do I need to initiate an empty list before list comprehension? - Python FAQ - Codecademy Forums
March 9, 2019 - Is there a good reason to initiate the empty list variable first ? It still works if I omit can_ride_coaster = [] before building the new list, and still gives a valid zero length list even if the height parameter is set so we get an empty list.
๐ŸŒ
datagy
datagy.io โ€บ home โ€บ python posts โ€บ how to check if a python list is empty
How to Check if a Python List is Empty โ€ข datagy
August 26, 2022 - Before we dive into learning how to check if a Python list is empty, letโ€™s quickly take a look at what Python lists are and how you can use them. A Python list is a heterogeneous, mutable, and iterable container object in Python. This means that lists can contain items of different data types, have items added, removed or changed, and that you can loop over these items. Letโ€™s take a look at a simple list and how we can iterate over a list: # Iterating Over a Simple List list1 = [1,2,3] for item in list1: print(item) # Returns: # 1 # 2 # 3
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71655820 โ€บ how-to-not-print-empty-list-in-for-loop-python
How to not print "empty" list in for loop - Python - Stack Overflow
In this case, all you need to do is add an if: if lst: print(lst). Also: don't name your variable list, it shadows the builtin type list ... As input_name is a string, then this is looping over the characters in the string, meaning you attempt ...