Reputation: 25
Recently I have had to make dynamically changing lists I iterate through in the main loop. But they are empty initially, and may be empty sometimes. Here are two cases:
# The first one
iterable = []
if iterable:
for i in iterable:
# do sth
# and the second
iterable = []
for i in iterable:
# do sth
I'm wondering if there is some difference in performance of these 2 cases, or the empty check is already implemented in the for loop?
Upvotes: 1
Views: 1736
Reputation: 627065
When you iterate over a define list variable, you do not encounter any problems, have a look:
>>> iterable=[]
>>> for x in iterable:
print(x)
>>>
The empty check is done automatically for you.
So, it is preferable to use the second code snippet in your question, because there is no redundant if iterable:
code line.
Upvotes: 1