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.

7
  • Could you do list(args) ? Commented Feb 16, 2020 at 18:58
  • I could, but this just creates a list, whereas I already have a list created and trying to append values. Commented Feb 16, 2020 at 19:08
  • Ah, you’re trying to append multiple values, I misunderstood. Commented Feb 16, 2020 at 19:09
  • 1
    Might this be a duplicate of stackoverflow.com/questions/3274095/append-tuples-to-a-list ? Commented Feb 16, 2020 at 19:10
  • 1
    The question is slightly confusing, but the accepted answer is just list.extend(). Commented Feb 16, 2020 at 19:13

2 Answers 2

5

You can use the list.extend method instead:

def add_grades(*args): grades.extend(args): return grades 
Sign up to request clarification or add additional context in comments.

Comments

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]) 

1 Comment

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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.