I want also note that in a case when x is a large size list you may want iterator to be returned after list filtering because using iterator on a large data set may increase your performance (See Performance Advantages to Iterators? for more information).
In this case you can use built-in filter(function, iterable) function that will return iterator in a Python 3.
x = ["f","f","f",0,"f",0,0,0,"f","f"]
for ch in filter(lambda sym: sym != 0, x):
print(ch)
As a result only elements not equal to 0 will be printed.
See https://docs.python.org/3/library/functions.html#filter to get more information about the filter built-in.
Another approach is to use generator comprehension. The note here is that you will be able to iterate over the generator just once. But you will also have some benefits, each result will be evaluating and yielding on the fly so your memory will be conserved by using a generator expression instead.
Just use this example to use generator comprehension:
x = ["f","f","f",0,"f",0,0,0,"f","f"]
for ch in (sym for sym in x if sym !=0):
print(ch)
See more generator comprehension examples and advantages here https://www.python.org/dev/peps/pep-0289/
Also be accurate filtering results with True value testing.
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
- None
- False
- zero of any numeric type, for example, 0, 0.0, 0j.
- any empty sequence, for example, '', (), [].
- any empty mapping, for example, {}.
- instances of user-defined classes, if the class defines a bool() or len() method, when that method returns the integer zero or bool value False.
So expression [sym for sym in x if sym]
will remove all False symbols (i.e. False, '', etc.) from your results. So be accurate using True value testing (see https://docs.python.org/3.6/library/stdtypes.html#truth-value-testing for more information).