0
my_list = [1,2,3,4,5,6,7,8,9,10]

gen_comp = (item for item in my_list if item > 3)

for item in gen_comp:
    print(item)
Georgy
  • 12,464
  • 7
  • 65
  • 73
  • 1
    It's a tuple comprehension. That one creates a tuple containing every item in my_list that have a value > 3. – Mandera Jun 14 '20 at 12:04
  • 1
    @Mandera Wrong! There is no such thing as a ["tuple comprehension"](https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python). This one is a [generator expression](https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions) and it doesn't create a tuple. – Georgy Jun 14 '20 at 12:28
  • Probably a better duplicate target: [Generator Expressions vs. List Comprehension](https://stackoverflow.com/q/47789/7851470) – Georgy Jun 14 '20 at 12:32
  • @Georgy Cool! Thank you – Mandera Jun 14 '20 at 12:34

1 Answers1

1

i added some comments, hope this help you:

# create a list with 10 elements
my_list = [1,2,3,4,5,6,7,8,9,10]

# generate a list based on my_list and add only items if the value is over 3
# this is also known as tuple comprehension 
# that one creates a tuple containing every item in my_list that have a value greater then 3. 
gen_comp = (item for item in my_list if item > 3)

# print the new generated list gen_comp
for item in gen_comp:
    print(item)

output:

4
5
6
7
8
9
10
Stefan Schulz
  • 533
  • 3
  • 8