2

Assume line is: "Chicago Sun 01:52".

What does *a, b, c = line.split() do? In particular, what is the significance of the asterisk?

Edit: Upon testing it, it seems like "Chicago", "Sun" and "01:52" are all stored in a, b and c. The asterisk seems to lead to "Chicago" being stored in a as the first element of a list. So, we have a = ["Chicago"], b = "Sun" and c = "01:52". Could anyone point to material on the functionality of the asterisk operator in this situation?

cs95
  • 379,657
  • 97
  • 704
  • 746
Sahand
  • 7,980
  • 23
  • 69
  • 137
  • What do you see in the variables when you try this? – Barmar Aug 24 '17 at 20:28
  • 2
    See documentation [PEP 3132 -- Extended Iterable Unpacking](https://www.python.org/dev/peps/pep-3132/) – AChampion Aug 24 '17 at 20:30
  • The asterisk means something of arbitrary length (called star unpacking). So everything up until the last three elements in your `line.split()` method – Mangohero1 Aug 24 '17 at 20:30

1 Answers1

4

Splitting that text by whitespace will give you:

In [743]: line.split()
Out[743]: ['Chicago', 'Sun', '01:52']

Now, this is a 3 element list. The assignment will take the last two elements of the output and assign them to b and c respectively. The *, or the splat operator will then pass the remainder of that list to a, and so a is a list of elements. In this case, a is a single-element list.

In [744]: *a, b, c = line.split()

In [745]: a
Out[745]: ['Chicago']

In [746]: b
Out[746]: 'Sun'

In [747]: c
Out[747]: '01:52'

Look at PEP 3132 and Where are python's splat operators * and ** valid? for more information on the splat operators, how they work and where they're applicable.

cs95
  • 379,657
  • 97
  • 704
  • 746