Mark
Mark

Reputation: 13

How to add 0's into two dimensional list using list comprehension in python?

I'm trying to convert this for loop into "list comprehension" format if possible:

This loop adds 0 into two dimensional list

test_list = [['string1'],['string2'],['string3']]
for i in range(len(test_list)):
    test_list[i].insert(1, 0)

output:

test_list = [['string1',0],['string2',0],['string3',0]]

I've tried this but for some reason it doesn't work.

test_list = [test_list[i].insert(1, 0) for i in range(len(test_list))]

Upvotes: 1

Views: 49

Answers (2)

nosklo
nosklo

Reputation: 223052

It doesn't work, because list.insert() modifies the list in-place and returns None, so you will end up with a list of Nones which are return values from all .insert()s.

List comprehension format is not adequate for what you want, because it is designed to create new lists, and you seem to want to modify the list in-place. If you want to create new lists instead, you can use this:

test_list = [sublist + [0] for sublist in test_list]

this works because the + operator on lists creates and returns a new list.

Upvotes: 2

Michael Lorton
Michael Lorton

Reputation: 44406

Is your question "what's the reason?"

The line

 test_list = [test_list[i].insert(1, 0) for i in range(len(test_list))]

means "make a list of the return values of this expression".

The return value of the expression [].insert() is None. test_list will be set to a list of Nones.

Upvotes: 0

Related Questions