Search code examples
pythonlist-comprehensionnested-lists

How to use a list comprehension to make the first item in a nested list 0?


For example if I have a list that is something like:

num_list = [
    [1234, 1244123, 453242], 
    [123123, 78421, 76433], 
    [46345, 578542, 47463]
]

and I need it to return

[
    [0, 1244123, 453242], 
    [0, 78421, 76433], 
    [0, 578542, 47463]
]

how would I go about doing this with a list comprehension?

I know how to do it with a nested for loop. I tried to do something along the lines of:

[[x * 0 for x in j[0]] for j in num_list]

Solution

  • num_list = [[0] + i[1:] for i in num_list]
    

    output:

    [[0, 1244123, 453242], [0, 78421, 76433], [0, 578542, 47463]]