Python next() Built in Function

The next() function in Python returns the next item from an iterator. An iterator is an object that can be iterated over, such as a list, tuple, string, etc. The next() function can also take a default value as a second argument, which is returned if the iterator has no more items.

Here are some examples of using next() function in Python:

Using next() with a list iterator

# This example creates an iterator from a list and prints its items one by one
mylist = iter(["apple" ,"banana" ,"cherry"])
x = next(mylist)

print(x) # Output: apple
x = next(mylist)
print(x)
# Output: banana
x = next(mylist)
print(x)
# Output: cherry

Using next() with a default value

# This example returns a default value when the iterator has reached its end
mylist = iter(["apple" ,"banana" ,"cherry"])
while True:
    item = next(mylist ,"end")
    if item == "end":
        break
    print(item)

# Output: apple banana cherry

Using next() with a generator

# This example creates a generator that yields odd numbers and prints them using next()
def odd_numbers():
    n = 1
    while True:
        yield n
        n += 2


gen = odd_numbers()
print(next(gen))
# Output: 1
print(next(gen)) # Output: 3
print(next(gen)) # Output: 5

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions