1

I been trying to code the following line but I get the message that operands could not be broadcast together with shapes (0,) (30,) x has a length of 32

  • x[:-N+1] I want to access all elements except the last two
  • x[N:-N] I want to access all elements except the first one and the last one
  • x[N+1:] I want to access all elements except the first
y = x[:-N+1] - 2 * x[N:-N] + x[N+1:]

How should I index x to access those values? I'm new to python so any tips would be appreciated.

user3840170
  • 26,597
  • 4
  • 30
  • 62
Brucee
  • 31
  • 6

2 Answers2

0

Slice except the last two: x[:N-2] Except first and last: x[1:N-1] Except first two: x[2:]

Python slice can be obtained by: x[starting_index:end_index] {including starting_index element and excluding end_index}

If you don't specify the starting_index, it becomes 0 by default. If you don't specify the end_index, it becomes N by default.

Yewgen_Dom
  • 66
  • 6
  • One word of caution: Slicing is that simple only while all numbers (start, end, step) are non-negative. – VPfB Jan 29 '22 at 19:45
0

Considering the list length might be vary, the python has good apporach to access the items of a list. Given a alist=['a','b','something',1,2]

if you use alist[1:], you will get ['b', 'something', 1, 2]

if you use alist[:1], you will get ['a','b','something',1]

if you only use alist[1], you will only get a ,which is the first item of the list.

so, if you use alist[-1:], you will get 2 , which is the first item starts from right.

if you use alist[:-1], you will get ['a','b','something',1] , which are items start from right except the fist.

In conclusion, the empty thing in the [:] is what you will get after use slicing.

wsq_star
  • 17
  • 1
  • 1
    _if you only use alist[1], you will only get a ,which is the first item of the list._ **wrong**: [1] returns the `second` item. – AcK Oct 08 '22 at 23:42