2

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?

0

1 Answer 1

6

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.