How to Generate a List of Consecutive Numbers

How can I generate a list of consecutive numbers?

In Python 3, you can use the builtin range function like this

>>> list(range(9))
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Note 1: Python 3.x's range function, returns a range object. If you want a list you need to explicitly convert that to a list, with the list function like I have shown in the answer.

Note 2: We pass number 9 to range function because, range function will generate numbers till the given number but not including the number. So, we give the actual number + 1.

Note 3: There is a small difference in functionality of range in Python 2 and 3. You can read more about that in this answer.

Generating a list of consecutive numbers as strings

>>> [str(i) for i in range(1,7)]
['1', '2', '3', '4', '5', '6']

Make a list of consecutive numbers in R

You can use as.list(1:4)

as.list(1:4)

[[1]] [1] 1

[[2]] [1] 2

[[3]] [1] 3

[[4]] [1] 4

EDIT

or as.list(seq(4))

EDIT #2

Here's a speed comparison using microbenchmark:

microbenchmark(as.list(1:4), as.list(seq(4)), Map(c,1:4), sapply(1:4, list), times=1e6)
Unit: microseconds
expr min lq mean median uq max neval
as.list(1:4) 1.472 2.088 2.639712 2.314 2.584 32594.44 1e+06
as.list(seq(4)) 3.934 5.359 6.514579 5.818 6.337 31498.31 1e+06
Map(c, 1:4) 3.435 5.052 6.243628 5.516 6.041 32628.84 1e+06
sapply(1:4, list) 6.892 9.358 11.282727 10.009 10.757 34269.70 1e+06

Python generate a list of consecutive numbers from a list of numbers

You can use a generator:

List1 = [1,2,3,7,8,11,14,15,16]
def groups(d):
c, start = [d[0]], d[0]
for i in d[1:]:
if abs(i-start) != 1:
yield c
c = [i]
else:
c.append(i)
start = i
yield c

results = [str(a) if not b else f'{a}:{b[-1]}' for a, *b in groups(List1)]

Output:

['1:3', '7:8', '11', '14:16']

Create a list of strings with consecutive numbers appended

You can concatenate them (the number and the word Period) together while the loop iterates.

Python 3.6+

print([f'Period {i}' for i in range(1, 14)])

Python 2.7+

print(['Period {}'.format(i) for i in range(1, 14)])

How do I create a list with numbers between two values?

Use range. In Python 2, it returns a list directly:

>>> range(11, 17)
[11, 12, 13, 14, 15, 16]

In Python 3, range is an iterator. To convert it to a list:

>>> list(range(11, 17))
[11, 12, 13, 14, 15, 16]

Note: The second number in range(start, stop) is exclusive. So, stop = 16+1 = 17.


To increment by steps of 0.5, consider using numpy's arange() and .tolist():

>>> import numpy as np
>>> np.arange(11, 17, 0.5).tolist()

[11.0, 11.5, 12.0, 12.5, 13.0, 13.5,
14.0, 14.5, 15.0, 15.5, 16.0, 16.5]

See: How do I use a decimal step value for range()?

Creating a list with sequential numbers fast

For full portability, list(range(N)) will get the best performance as Prune notes. That said, if you're purely targeting Python 3.5 or higher, you can use PEP 448's additional unpacking generalizations to speed it up a small amount, with:

[*range(N)]

Note that this is a fixed savings, not per-item; all it does is bypass the lookup of list in the built-in namespace, and the generalized function call dispatch and __init__ argument processing of the normal list constructor. So when you're talking about 100 million items, the savings are going to be lost in the noise; all this does is reduce the fixed overhead by (on my 3.6 install) 170±10 ns (e.g. list(range(0)) takes 417 ns per call, vs. 247 ns per call for [*range(0)]).

In specific cases though, there is an even faster option:

mynotlist = range(100000000)

In modern Python, range objects are full fledged sequences, they're just not mutable. So you can construct them, index them, slice them, compute their length, iterate them forwards and backwards, check membership (in O(1) for ints, unlike list where membership testing is O(n)), etc. The only non-mutability related features they lack are concatenation and repetition (with + and *), though you can simulate that with itertools functions like chain (for concatenation), and isliceing a cycle (for repetition).

If you don't need to mutate the sequence, just read from it, using the range "raw" is by far the best option; ranges are lazy, consuming no memory, while still producing their values extremely efficiently. That laziness can be important; list(range(100000000)) will require (on 64 bit Python) 3.45 gigabytes of memory for the list itself plus all the ints it contains; range(100000000) requires 48 bytes. The trivial cost of generating the values on the fly is more than worth it, given the memory savings.

If you need mutability, you can still save a bit on memory. If numpy is an option, sacul's answer has you covered; if not, Python's array module will save you a little bit of time, and a lot of memory. Compared to:

 list(range(100000000))

the array alternative:

 array.array('I', range(100000000))

takes about 10% less time (microbenchmarks had list at 3.39 sec, vs. array.array at 3.07 sec), and consumes far less memory (under ~391 MB, vs. the ~3529 MB of the list of ints). The main cost of array is limited range of values (e.g. for 'I', four byte unsigned ints can only store values in range(2**32); the maximum range for q/Q format codes, using twice the memory, would be range(-2**63, 2**63)/range(2**64)).

How to generate a list with a specific range of numbers

The initialization of the first list could be done in this way

Dim init As Integer = 1001
Dim myList As IEnumerable(Of Integer) = Enumerable.Range(start:=0, count:=15).
Select(Function(x) init + (x * 5))

The creation of the string result could be done with String.Join

Dim result = String.Join(Environment.NewLine, myList)
Console.WriteLine(result)

How to get all consecutive sequences of numbers from given set of numbers?

Here's how to do it:

list = [1,2,3,4]

sequancesList = []

for i in range(len(list)):
tmp = []
for j in range(i,len(list)):
tmp.append(list[j])
sequancesList.append(tmp[:])

print(sequancesList)

-> [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]



Related Topics



Leave a reply



Submit