kyrenia
kyrenia

Reputation: 5565

Append item to every list in list of list

I am looking to append item to every list in a list of list.

I had expected the following code to work:

start_list = [["a", "b"], ["c", "d"]]

end_list = [item.append("test") for item in start_list]

with expected output [["a", "b", "test"], ["c", "d", "test"]]

instead i get [None, None]

First, why does this occur, and second, how do i achieve the desired output?

Upvotes: 1

Views: 975

Answers (1)

Alex
Alex

Reputation: 19104

append modifies the list and returns None.

If you want to generate a new list:

end_list = [item + ["test"] for item in start_list]

If you want to modify the old list:

for sublist in start_list:
    sublist.append("test")

Upvotes: 6

Related Questions