-1

I do not understand what the '*' does in my code. What does it do and what is it called?

numbers = [x for x in range(5)]
mystrings = "numbers:{0}, {1}, {2}, {3}".format(*numbers)
print(mystrings)

I do not even know what it is called (or I would have searched online already). I was learning how to use String.format() and wanted to add items from a list without typing them all out manually. I found this solution but it came with no explanation.

This is what I was trying to avoid:

mystrings = "numbers:{0},{1},{2},{3}".format(numbers[0],
                                          numbers[1],
                                          numbers[2],
                                          numbers[3]
                                          )
  • https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/#Asterisks_for_unpacking_into_function_call – Hatshepsut Jul 06 '19 at 21:27

1 Answers1

0

In this context the * is usually called the splat operator, it takes a list of arguments and expands it - in this case it's needed because format() expects individual arguments, not a list. So yes, this:

*numbers

Is exactly the same as this (assuming a 4-element list, but works for any length):

numbers[0], numbers[1], numbers[2], numbers[3]
Óscar López
  • 232,561
  • 37
  • 312
  • 386