Going fast! #DataquestChallenge Premium Annual Offer:
500 get 50% & the next 1000 get 40% off.
GET OFFER CODE

Using the .append() method with two arguments

Hi,

I don’t understand why the latter code posted here works. Is anyone able to provide any further explanation for me please?

My Code:

import datetime as dt

result_list=[]

for row in ask_posts:
    created_at=row[6]
    num_comments=int(row[4])
    result_list.append(created_at,num_comments)

What I expected to happen:
List to be appended using two elements.

What actually happened:

TypeError                                 Traceback (most recent call last)
<ipython-input-26-c22dc31a5ca3> in <module>
      6     created_at=row[6]
      7     num_comments=int(row[4])
----> 8     result_list.append(created_at,num_comments)
      9 
     10 counts_by_hour={}

TypeError: append() takes exactly one argument (2 given)

I’ve researched the problem and know that I can fix it by using within the append method.

for row in ask_posts:
    created_at=row[6]
    num_comments=int(row[4])
    result_list.append([created_at,num_comments])

What is actually happening in this situation please?

1 Like

The error message explains all, .append() method takes exactly one argument.
since you want to append both created_at,num_comments it would be great if you append them as a tuple or list

import datetime as dt

result_list=[]

for row in ask_posts:
    created_at=row[6]
    num_comments=int(row[4])
    result_list.append((created_at,num_comments))

OR

import datetime as dt

result_list=[]

for row in ask_posts:
    created_at=row[6]
    num_comments=int(row[4])
    result_list.append([created_at,num_comments])

Reasons

The append() method in python adds a single item to the existing list.

4 Likes

Hello @c.smyth1992, welcome to the community!

The error says that append() takes exactly one argument. That’s the reason you got the error in the first code: you passed two arguments.

In the second code, you put these two items into a list and passed the list as the only argument. Therefore, you passed only one argument as append() requires.

2 Likes

Thank you very much for the prompt responses.

That makes a lot of sense, I didn’t expect the solution to be so straightforward!

2 Likes

Thanks so much! It solved my problems