Sets can take their contents from an iterable and let you iterate over the set’s elements: S ={ 2,3,5,7,11 ,13 } for i in S: print(i) line_list=[' line 1 ','line 2 ',...] # Generator expression -- returns iterator stripped_iter =(line.strip() for line in line_list) # List comprehension -- returns list stripped_list=[line.strip() for line in line_list] ( expression for expr in sequence1 if condition1 for expr2 in sequence2 if condition2 for expr3 in sequence3... if condition3 for exprN in sequenceN if conditionN ) 6 The$_{for...in}$ clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are iterated over from left to right, not in parallel. For each element in$_{sequence1}$ ,$_{sequence2}$ is looped over from the beginning. sequence3 is then looped over for each resulting pair of elements from sequence1 and$_{sequence2}$ . obj_total=sum(obj.count for obj in list_all_objects()) Generator expressions always have to be written inside parentheses, but the parentheses signalling a function call also count. If you want to create an iterator that will be immediately passed to a function you can write: The elements of the generated output will be the successive values of$_{expression}$. The$_{if}$ clauses are all optional; if present,$_{expression}$ is only evaluated and added to the result when$_{condition}$ is true. Again, for a list comprehension only the outside brackets are different (square brackets instead of parentheses). Generator expressions are surrounded by parentheses (“()”) and list comprehensions are surrounded by square brackets (“[]”). Generator expressions have the form: With a list comprehension, you get back a Python list;$_{stripped_list}$is a list containing the resulting lines, not an iterator. Generator expressions return an iterator that computes the values as necessary, not needing to materialize all the values at once. This means that list comprehensions aren’t useful if you’re working with iterators that return an infinite stream or a very large amount of data. Generator expressions are preferable in these situations. stripped_list=[line.strip() for line in line_list if line !=""] You can select only certain elements by adding an$_{"if"}$ condition: List comprehensions and generator expressions (short form: “listcomps” and “genexps”) are a concise notation for such operations, borrowed from the functional programming language Haskell (https://www.haskell.org/). You can strip all the whitespace from a stream of strings with the following code: Two common operations on an iterator’s output are 1) performing some operation for every element, 2) selecting a subset of elements that meet some condition. For example, given a list of strings, you might want to strip off trailing whitespace from each line or extract all the strings containing a given substring. 3 Generator expressions and list comprehensions