Mateus Forcelini
Mateus Forcelini

Reputation: 111

Python: creating a tuple with predetermined length

I'm working on a Python problem where I need to set up a tuple with a pre-defined length n (being n an input of the program), where each element must have a specific float value (e.g. H), similar to what is possible to do with NumPy arrays in this way:

import numpy as np

arr = H*np.ones(n)

Is it possible for a tuple?

Upvotes: 1

Views: 2257

Answers (1)

mkrieger1
mkrieger1

Reputation: 23192

You can create one with a generator expression:

tuple(H for _ in range(n))

Instead of a constant value H you can fill the tuple with an arbitrary expression depending on the iteration variable (which was not used above and therefore named _ by convention):

tuple(f(i) for i in range(n))

For example, to fill the first half with G and the second half with H, you can use a conditional expression as f(i):

tuple(G if i < n/2 else H for i in range(n))

Upvotes: 5

Related Questions