The sea does not like to be restrained.
Emektar Üye
- Katılım
- 15 Tem 2021
- Mesajlar
- 1,724
- Çözümler
- 86
- Tepki puanı
- 665
- Ödüller
- 10
- Yaş
- 25
- Sosyal
4 HİZMET YILI
Generators are functions that allow you to iterate over a sequence of values, one at a time, without creating the entire sequence in memory at once. Instead, the values are generated on-the-fly as you iterate over them. This makes generators especially useful for working with large or infinite sequences, where it would be impractical or impossible to generate the entire sequence in memory.
In Python, you can create a generator function using the yield keyword instead of return. Here's an example:
In this example, fibonacci() is a generator function that yields the next value in the Fibonacci sequence each time it is called. When we call fibonacci(10) in the for loop, it returns a generator object, which we can then use to iterate over the first 10 Fibonacci numbers.
One advantage of generators is that they are lazy-evaluated, meaning that the values are generated only when they are needed. This can be more memory-efficient than creating a list or other data structure containing all the values at once.
You can also use generator expressions, which are similar to list comprehensions, but generate a sequence of values on-the-fly instead of creating a list. Here's an example:
In this example, we use a generator expression to create a sequence of squares from 0 to 81. We then use a for loop to iterate over the squares, but break out of the loop when we reach a square greater than 25.
In Python, you can create a generator function using the yield keyword instead of return. Here's an example:
Python:
def fibonacci(n):
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
# generate the first 10 Fibonacci numbers
for number in fibonacci(10):
print(number)
In this example, fibonacci() is a generator function that yields the next value in the Fibonacci sequence each time it is called. When we call fibonacci(10) in the for loop, it returns a generator object, which we can then use to iterate over the first 10 Fibonacci numbers.
One advantage of generators is that they are lazy-evaluated, meaning that the values are generated only when they are needed. This can be more memory-efficient than creating a list or other data structure containing all the values at once.
You can also use generator expressions, which are similar to list comprehensions, but generate a sequence of values on-the-fly instead of creating a list. Here's an example:
Python:
squares = (x ** 2 for x in range(10))
# iterate over the first 5 squares
for square in squares:
if square > 25:
break
print(square)
In this example, we use a generator expression to create a sequence of squares from 0 to 81. We then use a for loop to iterate over the squares, but break out of the loop when we reach a square greater than 25.