Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does 'a, b, c = input().split()' mean in Python?

a, b, c = input().split()

I have encountered a problem while learning python programming, i think this is a basic problem but i don’t understand how that statement works.
Can anyone help me with the answer?

Thank you everyone!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is known commonly as iterable unpacking. If an item is iterable, you can use it to initialize multiple variables at once. A common pattern you’ve probably already seen is tuple unpacking, such as:

a, b = 1, 2

This is somewhat equivalent to writing:

vals = (1, 2)
a = vals[1]
b = vals[2]

It is possible to perform this on more than just tuples. Here’s some examples which all produce similar results:

a, b = 1, 2
a, b = [1, 2]

# Note: when a set is used as an iterable, 
# the ordering of assignment is undefined.
a, b = {1, 2}

# Note: when a dictionary is used as an iterable, 
# only the keys are evaluated
a, b = {1: 'a', 2: 'b'}

# You can also use a generator:
def foo():
    yield 1
    yield 2

a, b = foo()

For the above examples to work, the size of the iterable must match the number of arguments provided. For example:

>>> a, b = 1, 2, 3
Traceback (most recent call last):
  File "...", line 1, in <module>
    a, b = 1, 2, 3
    ^^^^
ValueError: too many values to unpack (expected 2)

In cases where there are an unknown amount of variables and you only want to grab a certain set of them, you can use Extended Iterable Unpacking. In this method you can define a variable in the expansion as a catch-all. From the linked PEP, you have the example:

>>> a, *b, c = range(5)
>>> a
0
>>> c
4
>>> b
[1, 2, 3]

Iterable unpacking can also be used in for loops, which is very commonly used when iterating through a dictionary. dict.items() returns an iterable of pair iterables, allowing you to write code such as this:

>>> data = {1:2, 3:4}
>>> for key, value in data.items():
...     print(key, value)
1 2
3 4

Unpacking can also be used in more nested contexts, allowing you to unpack some pretty complex structures, so use it mindfully!

>>> data = [
...     [1, [2, [3, 4, 5, 6]]],
...     [1, [2, [3, 4, 5, 6, 7]]],
... ]
>>> for a, [b, [c, *_, d]] in data:
...     print(a, b, c, d)
1 2 3 6
1 2 3 7
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading