Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create range without certain numbers

Tags:

python

range

I want to create a range x from 0 ... n, without any of the numbers in the list y. How can I do this?

For example:

n = 10
y = [3, 7, 8]
x = # Do Something

Should give the output:

x = [0, 1, 2, 4, 5, 6, 9]

One naive way would be to concatenate several ranges, each spanning a set of numbers which have been intersected by the numbers in y. However, I'm not sure of what the simplest syntax to do this is in Python.

like image 321
Karnivaurus Avatar asked Aug 18 '14 17:08

Karnivaurus


People also ask

How do you exclude numbers from a range in Python?

If you want to exclude 0 then change your range to (1,11). The way range works is the lower limit is inclusive where as upper limit is exclusive. On an unrelated note, if your lower limit is 0, you need not include the lower limit and write it as range(11) which is same as range(0,11).

How do you skip a value in Python?

Use the continue statement inside the loop to skip to the next iteration in Python. However, you can say it will skip the current iteration, not the next one.

How do I make a list of certain ranges in Python?

To convert a Python Range to Python List, use list() constructor, with range object passed as argument. list() constructor returns a list generated using the range. Or you can use a for loop to append each item of range to list.

How do you make a list 0 to N in Python?

Use the range() Function to Create a List of Numbers From 1 to N. The range() function is very commonly used in Python. It returns a sequence between two numbers given in the function arguments. The starting number is 0 by default if not specified.


2 Answers

You can use a list comprehension to filter the range from 0 to n: range(n) generates a list (or, in Python 3, a generator object) from 0 to n - 1 (including both ends):

x = [i for i in range(n) if i not in y]

This filters out all numbers in y from the range.

You can also turn it into a generator (which you could only iterate over once but which would be faster for (very) large n) by replacing [ with ( and ] with ). Further, in Python 2, you can use xrange instead of range to avoid loading the entire range into memory at once. Also, especially if y is a large list, you can turn it into a set first to use O(1) membership checks instead of O(n) on list or tuple objects. Such a version might look like

s = set(y)
x = (i for i in range(n) if i not in s)
like image 199
hlt Avatar answered Oct 05 '22 22:10

hlt


hlt's answer is ideal, but I'll quickly suggest another way using set operations.

n = 10
y = [3, 7, 8]
x = set(range(n)) - set(y)

x will be a set object. If you definitely need x to be a list, you can just write x = list(x).

Note that the ordering of a set in Python is not guaranteed to be anything in particular. If order is needed, remember to sort.

like image 43
Alex Riley Avatar answered Oct 05 '22 23:10

Alex Riley