Python provides many friendly advanced API for programmer, one of which is unpacking. By unpacking, it means getting all the elements from a container. A simplest case in the below demonstrates assigns the two items in tuple to variables.

```
>>> a, b = (1,2)
>>> a
1
>>> b
2
```

Besides tuple, every iterative object can support unpacking, such as list, dictionary, set, string, generator etc. Let’s traverse them one by one.

# List Unpacking

```
>>> a, b, c = [1,2,3]
>>> a,b,c
(1,2,3)
```

Sometimes when we only care about certain parts of a list when unpacking, a dummy variable like `_`

is used as placeholder, as in the example below.

```
>>> a, _, c = [1,2,3]
>>> a,c
(1,3)
```

# String Unpacking

```
>>> a,b,c = "abc"
>>> a,b,c,
('a', 'b', 'c')
```

# Dictionary Unpacking

```
>>> a, b, c = {"a":1, "b":2, "c":3}
>>> a,b,c,
('a', 'b', 'c')
```

After unpacking, the values in the previous dictionary are discarded.

# Multiple Assignment

Actually, multiple assignment is also a unpacking since the right side of equal sign is a tuple.

```
>>> a, b = 1, 2
>>> a
1
>>> b
2
```

So you can infer that swapping two variables also involves unpacking.

```
>>> a, b = 1, 2
>>> a, b = b, a
>>> a
2
>>> b
1
```

A veteran may query what would happened if the numbers of two sides are not equal? The answer is a `ValueError`

.

```
>>> a, b, c = [1, 2, 3, 4]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-21-1abe27b4224b> in <module>()
----> 1 a, b, c = [1, 2, 3, 4]
ValueError: too many values to unpack (expected 3)
```

We can avoid this situation by `*`

operator introduced by Python 3.

```
>>> a, b, *c = [1,2,3,4]
>>> a
1
>>> b
2
>>> c
[3, 4]
>>>
```

A more further question is how about using `*`

in the middle of variables. Yes, Python is so smart.

```
>>> a, *b, c = [1,2,3,4]
>>> a
1
>>> b
[2, 3]
>>> c
4
```

You can also do the same thing to a dictionary.

```
>>> a, *b, c = {"a":1, "b":2, "c":3,"d":4}
>>> b
['b', 'c']
```

For more about `*`

and `**`

, please switch to *args and **kwargs Usage in Python

**Reference**