ChessMaster
ChessMaster

Reputation: 549

About slices in Python

  1. Is there any difference between mylist[:] and mylist[::]?
  2. What's the rationale for mylist[::0] to raise an error since negative steps are allowed?

Upvotes: 4

Views: 8067

Answers (3)

avasal
avasal

Reputation: 14864

No difference between mylist[:] and mylist[::]

mylist[::0]

This implies from starting index to last index without any step, don't know in what world it would be possible.

Upvotes: 1

Neel
Neel

Reputation: 21315

Third element is for steps. When you write mylist[:] it will assume step will be 1 which is same case in mylist[::].

If you write mylist[::0] then it will raise error because steps can be +ve or -ve not 0

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799230

  1. No. Both result in slice(None, None, None).

  2. Positive strides go forwards. Negative strides go backwards. Zero strides go... nowhere? How exactly would that work? An infinite sequence of a single value?

Upvotes: 8

Related Questions