Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list with infinite elments

Tags:

python

I need to operate on two separate infinite list of numbers, but could not find a way to generate, store and operate on it in python.

Can any one please suggest me a way to handle infinite Arithmetic Progession or any series and how to operate on them considering the fact the minimal use of memory and time.

Thanks every one for their suggestions in advance.

like image 327
Somesh Avatar asked Dec 17 '12 07:12

Somesh


People also ask

Can a list be infinite?

Infinite lists, whose elements are evaluated upon demand, can be implemented using functions as data. The tail of a lazy list is a function that, if called, pro- duces another lazy list. A lazy list can be infinitely long and any finite number of its elements can be evaluated.

Can you make an infinite list in Python?

Lists do not have a built-in limit, but your computer hardware and the Jupyter kernel has a limit of available memory. If you need to work with large amount of data, use generators, and generator expressions. Do not put all the values in a list, but evaluate them one by one.

How do you create a list in Python?

In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.). A list can also have another list as an item.

How do you make the length of a list N in python?

To create a list of n placeholder elements, multiply the list of a single placeholder element with n . For example, use [None] * 5 to create a list [None, None, None, None, None] with five elements None . You can then overwrite some elements with index assignments.


2 Answers

You are looking for a python generator instead:

def infinitenumbers():
    count = 0
    while True:
        yield count
        count += 1

The itertools package comes with a pre-built count generator.

>>> import itertools
>>> c = itertools.count()
>>> next(c)
0
>>> next(c)
1
>>> for i in itertools.islice(c, 5):
...     print i
...
2
3
4
5
6
like image 123
Martijn Pieters Avatar answered Nov 15 '22 21:11

Martijn Pieters


This is where the iterator comes in. You can't have an infinite list of numbers, but you can have an infinite iterator.

import itertools
arithmetic_progression = itertools.count(start,step) #from the python docs

The docs for Python2 can be found here

like image 39
Snakes and Coffee Avatar answered Nov 15 '22 21:11

Snakes and Coffee