# How To Use Shuffle Function In Python

The Python `random` module `shuffle()` method shuffles all elements of a list in random order. This article will introduce how to use the `random` module `shuffle()` method in Python with examples.

### 1. Python Random Module Shuffle Method Introduction.

1. The `shuffle()` method usage syntax.
```# import the python random module
import random

# invoke the random module's shuffle method and pass a python list object.
random.shuffle(list
```
2. The `shuffle()` method argument can be a list or a tuple object.
3. The `shuffle()` method will randomly sort the elements in the list object.

### 2. Use Python Random Module Shuffle Mehotd To Shuffle List Elements In Random Order Example.

1. Shuffle integer number list example.
```>>> list = [1,2,3,4,5,6,7,8,9,10]
>>>
>>> print(list)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
>>> random.shuffle(list)
>>>
>>> print(list)
[4, 5, 10, 1, 8, 3, 7, 6, 2, 9]
>>>
>>> random.shuffle(list)
>>>
>>> print(list)
[3, 8, 2, 1, 5, 9, 4, 6, 7, 10]
>>>
```
2. Shuffle string list example.
```>>> import random
>>>
>>> list = ['I', 'love', 'python']
>>>
>>> print(list)
['I', 'love', 'python']
>>>
>>> random.shuffle(list)
>>>
>>> print(list)
['python', 'I', 'love']
>>>
```
3. You can not shuffle a python tuple object. If you pass a tuple object to `random.shuffle` method, it will throw TypeError: ‘tuple’ object does not support item assignment.
```>>> print(tuple)
('I', 'love', 'java')
>>>
>>> random.shuffle(tuple)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/random.py", line 278, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'tuple' object does not support item assignment```

This site uses Akismet to reduce spam. Learn how your comment data is processed.