hash_ir hash_ir - 1 year ago 65
Python Question

What do these lines of code do?

I am working with

. I encountered this line of code.

a = (1.,80.,5.)

What does this mean? At some other line, I found

aList = np.arange(a[0], a[1]+a[2], a[2])

is included from

Answer Source

a is a tuple of floats. A tuple is a kind of structure that is kinda like a list, but is immutable (i.e. you cannot modify any of its components once it has been created). But, like a list it can be indexed.

In theory, some tuples have special names, for example a tuple of 2 is called a pair, a tuple of 3 is called a triplet etc (people don't necessarily call them that, but it helps a bit more to understand what a tuple is about). Because it's immutable, conceptually it is thought of more as a unique object, rather than as a collection of ones; for this reason it can also be validly used as a key to a dictionary (as opposed to lists which cannot).

To create a tuple, you create a comma-separated sequence of objects inside parentheses, i.e. () (as opposed to brackets, i.e. [] that you would to create a list).

As for floats, the float 3.0 can also be written 3. for short.

The numpy.arange function then creates a range by calling it using the components of the tuple as arguments. In your particular case, it will create a range of numbers from 1 to 80+5, at increments of 5.

A very cool use of tuples is that they can be expanded into a sequence of arguments to a function. e.g. if you had a tuple a = (1.,10.,2.), and you wanted to call numpy.arange(a[0], a[1], a[2]), you could just do numpy.arange(*a) instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download