3

Suppose that:

h=[1,2,3]

There is operation N[expr] in Mathematica that gives us:

N[h[0]]=1, N[h[1]]=2, N[h[2]]=3

and for example N[h[6]]=0, is something like this in Python?

shadowspawn
  • 3,039
  • 22
  • 26
BASU
  • 49
  • 1
  • 3
  • 1
    this example code is not syntactically correct mathematica. what exactly are you trying to do? – agentp Nov 19 '16 at 12:35

2 Answers2

1

N[expr] in mathematica gives you the numeric value oft an expression. This makes sense in mathematica, which dos symbolic math.

In Python you normally don't have symbolic expressions (unless using specialized libraries such as sympy).

You can convert objects to integers using int. For example, int(2), int('2'), or int(2.6) result in the value 2. Or you can convert to floating point using float.

MB-F
  • 22,770
  • 4
  • 61
  • 116
0

Accesing out-of-bound value in Python using [..] operator in Python raises IndexError.

>>> h = [1, 2, 3]
>>> h[0]
1
>>> h[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

By catching IndexError, you can have similiar operation using a custom function:

>>> def N(sequence, index, fallback=0):
...     try:
...         return sequence[index]
...     except IndexError:
...         return fallback
...
>>> h = [1, 2, 3]
>>> N(h, 0)
1
>>> N(h, 1)
2
>>> N(h, 2)
3
>>> N(h, 6)
0
>>>
>>> N(h, 6, 9)  # different fallback value other than 0
9
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • I think the easiest way is: h=[1,2,3] for n in range(3,100): h.append (0) But, my question is is there any operation for this? for example by having an operation N. (Not defining an other algorithm) – BASU Nov 19 '16 at 08:35
  • You can also use `h.extend([0] * 97)` – falsetru Nov 19 '16 at 08:37