@a.xitas You are getting a list instead of a list of lists because that’s what your code is doing. You see, every row is a list. So when you go through ask_posts and get row you get that list. But then you get the items created_at and num_comments from the list and you append them separately to result_list. So, every time you go through the loop, 2 different items get added to result_list.
Now, if I am not mistaken, what you want is to add those two items to result_list but add them as a list. Am I right? If yes, then what we have to do is create a new list containing them both and append that list to result_list. What you are missing right now is the part where you create that new list.
I do not want to rob you of the fun of doing this yourself now that you know what’s wrong. So, I suggest you give it a try and if you are having trouble still you let us know. How does that sound?
I thought about that solution, but I was thinking in a slightly different way! I was creating 2 different lists, one for each variable and then trying to “add” that 2 different lists into a final one, a list of lists! But I was encountering various problems, 1st trying to “add” 2 lists together using the append method. I found it was not possible. Than I thought about the extend method, but once again this did not result into a list of lists with [[el1, el2], [el1, el2]…]. Also, the pure and simple add(+) a list to a list was not an option. So I got stuck and abandoned this solution. Then I read your comment. And I said, hhmmm, lets give it a try, but once again, I could not get the result I wanted:
import datetime as dt
result_list = []
data_hora_n_comentarios = []
for row in ask_posts:
created_at = row[6]
num_comments = row[4]
data_hora_n_comentarios.append(created_at)
data_hora_n_comentarios.append(num_comments)
result_list.append(data_hora_n_comentarios)
print(result_list)
So I was getting frustrated until I saw the other comment
I knew one way was trough list comprehension but I did not knew how to use it with 2elements/2lists. Now I know
Ah, so what’s happening here is you were simply making a giant list of lists.
After your for loop, your result_list had variables in the following form: [a, b, c, d, e, f]
You were getting the above because you were simply appending everything into one giant list!
What you needed to make was something closer to the following: [[a, b], [c, d], [e, f]]
You should be able to do this by changing your code like so:
result_list = []
for row in ask_posts:
created_at = row[6]
num_comments = row[4]
result_list.append([created_at, num_comments])
print(result_list)
Above, you’re appending the two objects together as a list directly into result_list to get the correct kind of list of lists.
The list comprehension method you see above worked because it also took into account that the row[6] and row[4] variables had to be together in their own individual lists.