Is there any way to set list value in integer range in python

I want to do the following:

>>> [0-2, 4]  #case 1
[-2, 4]     #I want the output to be [0, 1, 2, 4]

I know I can do the same:

>>> list(range(3)) + [4]   #case 2
[0, 1, 2, 4]

But I'm curious if there is a way to achieve the same result using the case 1 method (or something similar)? Do I need to redefine the integer operator "-" or do I need to do something with the list?

+4
source share
2 answers
>>> [*range(0,3), 4]
[0, 1, 2, 4]

Is approaching. Python 3 only.

+8
source

The answer is @timgebgreat, but it returns list, and by default the range returns "an immutable sequence type", and so use itertools.chainwill give iterablethat is more closely related to range().

import itertools
itertools.chain(range(3), range(4,5))

( list list(), ), :

[0, 1, 2, 4]

generator:

def joinRanges(r1, r2):
    for i in r1:
        yield i
    for i in r2:
        yield i

, , :

joinRanges(range(3), range(4,5))
+1

Source: https://habr.com/ru/post/1689977/


All Articles