user1786283
user1786283

Reputation:

Range in Python

I want to list numbers in range and I want to find out the amount of numbers in range.

For Example:

X = (5,6,5,1,2,3,4,5,6,7)
Y = (5, 5, 5,5 5,5 5,5 5)
range(X) # Want to know how many numbers in X.

If you guys could help it would be great.

Upvotes: 0

Views: 4614

Answers (5)

Andrew Rasmussen
Andrew Rasmussen

Reputation: 15099

filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true.

So you can do filter(range(2, 10).__contains__, x), which will return the elements in x which are in range(2, 10).

If you want to narrow this down to unique elements, call set:

set(filter(range(2, 10).__contains__, x))

Finally, if you want the number of these elements, simply call len:

len(filter(range(2, 10).__contains__, x))

this will return the number of elements in array x which are in range 2 to 10.

Upvotes: 2

jterrace
jterrace

Reputation: 67063

Given the tuple or list X:

>>> X = (5,6,5,1,2,3,4,5,6,7)
>>> X
(5, 6, 5, 1, 2, 3, 4, 5, 6, 7)

You find the number of elements with the len function:

>>> len(X)
10

If you want to find the number of unique elements, create a set and look at its length:

>>> set(X)
set([1, 2, 3, 4, 5, 6, 7])
>>> len(set(X))
7

The range (defined mathematically) of the set of numbers can be found with the max and min functions:

>>> (min(X), max(X))
(1, 7)
>>> max(X) - min(X)
6

Upvotes: 10

maaudet
maaudet

Reputation: 2358

I'm not sure if I understand exactly what you want, but to get the mathematical range:

max(X) - min(X)

Were max() gets the highest value and min() gets the lowest one.

Upvotes: 1

Rag
Rag

Reputation: 6593

Are you looking for:

X = (5,6,5,1,2,3,4,5,6,7)
range = max(X) - min(X)

Upvotes: 3

GaretJax
GaretJax

Reputation: 7780

I'm not sure I understand your question, but the number of numbers in X is the length of X:

len(X)

Upvotes: 1

Related Questions