简体   繁体   中英

While loop with single quotes for a condition in Python

I came across the following line of code in Python and I keep wondering what does it do exactly:

while '' in myList:
    myList.remove('')

Thanks in advance.

It removes all empty strings from a list, inefficiently.

'' in myList tests if '' is a member of myList ; it'll loop over myList to scan for the value. myList.remove('') scans through myList to find the first element in the list that is equal to '' and remove it from the list:

>>> myList ['', 'not empty']
>>> '' in myList
True
>>> myList.remove('')
>>> myList
['not empty']
>>> '' in myList
False

So, the code repeatedly scans myList for empty strings, and each time one is found, another scan is performed to remove that one empty string.

myList = [v for v in myList if v != '']

would be a different, more efficient way of accomplishing the same task. This uses a list comprehension; loop over all values in myList and build a new list object from those values, provided they are not equal to the empty string.

Put simply, it removes all empty strings from myList .

Below is a breakdown:

# While there are empty strings in `myList`...
while '' in myList:
    # ...call `myList.remove` with an empty string as its argument.
    # This will remove the one that is currently the closest to the start of the list.
    myList.remove('')

Note however that you can do this a lot better (more efficiently) with a list comprehension :

myList = [x for x in myList if x != '']

or, if myList is purely a list of strings:

# Empty strings evaluate to `False` in Python
myList = [x for x in myList if x]

If myList is a list of strings and you are on Python 2.x, you can use filter , which is even shorter:

myList = filter(None, myList)

In Python, two single quotes '' or double quotes "" represent the empty string.

The condition to keep looping is while the empty string exists in the list, and will only terminate when there are no more empty strings.

Therefore, it removes all empty strings from a list.

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