简体   繁体   中英

No Index Error in Conditional within List Comprehension

When I run the code:

mylist = []
mylist[1]

I get IndexError: list index out of range. This makes sense to me. But when I run the following code:

mylist = []
newlist = [x for x in mylist if mylist[1] == 'mystring']
print(newlist)

I don't get an index error, it just prints an empty list. This is what I want the code to do, but I don't understand why it doesn't give me and IndexError. From what I can tell, this only occurs when the the list is empty, otherwise you could get an index error if you indexed the list out of range. For example:

mylist = ['string']
newlist = [x for x in mylist if mylist[1] == 'mystring']

returns the IndexError I would expect it to return.

If anyone could help explain why if you have a conditional statement specifying an index of an empty list in a list comprehension, you don't get an index error, that would be fantastic.

This has nothing to do with conditionals and comprehensions. It's simply the fact that iterating over an empty sequence or collection produces no iterations. Notice how the following code block doesn't produce an error in the for loop, even though x is not defined:

>>> a = 0
>>> for i in []:
...     x = x + 2
...
>>> a
0
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Since mylist is already empty, for x in mylist will never iterate so if check will never be executed. Same thing applies for normal for loops as well:

>>> mylist = []
>>> for x in mylist:
...     print "second item", mylist[1]

# will print nothing

[x for x in mylist if mylist[1] == 'mystring'] ,对于每个迭代都执行if mylist[1] == 'mystring'子句-但由于mylist为空,因此迭代次数为零,因此它根本没有执行。

The expression if mylist[1] == 'mystring' is evaluated for each value in mylist .

As mylist is empty, the expression is never evaluated.

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