1

Hello and thanks for your time;

I am using *args to take various arguments, which creates a tuple. How do I 'unpack' a tuple into a list? The following code appends the list with a tuple.

grades = []

def add_grades(*args):
    grades.append(args):
    return grades

print(add_grades(99,88,77))

I can do this using a for loop and iterating through the tuple, but looking to see if I can unpack directly.

JulienEast
  • 27
  • 7

2 Answers2

5

You can use the list.extend method instead:

def add_grades(*args):
    grades.extend(args):
    return grades
blhsing
  • 91,368
  • 6
  • 71
  • 106
3

To convert the tuple to list you can return *args as list and extend the existing list

grades = []

def add_grades(*args):
    return [*args]

grades.extend(add_grades(99,88,77))

Note that you can extend the list with tuple as well

def add_grades(*args):
    return args

grades.extend(add_grades(99,88,77))

If you don't do anything else in add_grades you can also do it without any function

grades.extend([99,88,77])
Guy
  • 46,488
  • 10
  • 44
  • 88
  • 1
    Thanks - it seems that extend() takes any tuple arguments and adds them to a list, which was what I was looking for (and included in the two first answers) – JulienEast Feb 16 '20 at 19:30