vincent vincent - 1 year ago 82
Python Question

Shuffling a list in python

I have a python list object that has the following list,

a=[1, 2, 3, 0, 4].

I wanted to shuffle it with the following code:

from random import shuffle

But what's meaning of below code:

[4, 0, 3, 2, 1] # output

I know slice indices of python. But I've never seen above form before. So,I don't understand why that works?


Answer Source

Using the mylist[::-1] syntax, as asked, reverses a list. It does NOT shuffle the list.

Python Extended Slice Syntax

Negative values also work to make a copy of the same list in reverse order:

>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]