w3resource

Python: Create a list with infinite elements

Python List: Exercise - 53 with Solution

Write a Python program to create a list with infinite elements.

Sample Solution:

Python Code:

# Import the 'itertools' module to work with iterators and generators
import itertools

# Create an iterator 'c' using the 'count' function from 'itertools'
# The 'count' function generates an infinite sequence of numbers starting from 0
c = itertools.count()

# Use the 'next' function to retrieve the next value from the iterator 'c' and print it
print(next(c))

# Retrieve and print the next value from the iterator 'c'
print(next(c))

# Retrieve and print the next value from the iterator 'c'
print(next(c))

# Retrieve and print the next value from the iterator 'c'
print(next(c))

# Retrieve and print the next value from the iterator 'c'
print(next(c)) 

Sample Output:

0                                                                                                             
1                                                                                                             
2                                                                                                             
3                                                                                                             
4

Flowchart:

Flowchart: Create a list with infinite elements

Python Code Editor:

Previous: Write a Python program to compute the difference between two lists.
Next: Write a Python program to concatenate elements of a list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.