Arham Siddiqui
Arham Siddiqui

Reputation: 125

How do I use range to make a list with other values?

I currently want the following output:

[161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 13362, 13363, 13364, 13365, 13366, 13367, 13368, 13369, 13370, 13383, 13384, 11100, 667, 6503, 6506, 666]

(more condensed version:)

[161...172, 13362...13370, 13383, 13384, 11100, 667, 6503, 6506, 666]

So I figured out to do it like this:

emoteIds = range(161, 173)
for i in range(13362, 13371):
    emoteIds.append(i)
for i in [13383, 13384, 11100, 667, 6503, 6506, 666]:
    emoteIds.append(i)

However, I feel that this can be condensed. Is there any way for me to incorporate range() in the list without it making another list in the list? I tried using the list() function, but to no avail.

Upvotes: 0

Views: 70

Answers (2)

Divakar
Divakar

Reputation: 221514

With numpy.r_ that does the range creating under the hood for you -

 np.r_[161:173, 13362:13371, 13383, 13384, 11100, 667, 6503, 6506, 666]

Sample run -

In [461]: np.r_[161:173, 13362:13371, 13383, 13384, 11100, 667, 6503, 6506, 666]
Out[461]: 
array([  161,   162,   163,   164,   165,   166,   167,   168,   169,
         170,   171,   172, 13362, 13363, 13364, 13365, 13366, 13367,
       13368, 13369, 13370, 13383, 13384, 11100,   667,  6503,  6506,   666])

If you need a list as output, use .tolist() method at the end -

np.r_[161:173, 13362:13371, 13383, 13384, 11100, 667, 6503, 6506, 666].tolist()

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121406

You don't need to use loops; just concatenate the list objects:

emoteIds = range(161, 173) + range(13362, 13371) + [
    13383, 13384, 11100, 667, 6503, 6506, 666]

(In Python 3, you'd have to use list() calls to convert the range() objects to actual lists).

You may want to look at list.extend() as well; you could have used:

emoteIds = range(161, 173)
emoteIds.extend(range(13362, 13371))
emoteIds.extend([13383, 13384, 11100, 667, 6503, 6506, 666])

or a += augmented assignment, which comes down to the same thing as list.extend() here:

emoteIds = range(161, 173)
emoteIds += range(13362, 13371))
emoteIds += [13383, 13384, 11100, 667, 6503, 6506, 666]

Upvotes: 2

Related Questions