Search code examples
pythonlistnestedassign

Easier way to assign a value to the first element of each sub list?


I defined a nested list like this:

 T=[[0 for i in range(4)] for i in range(4)]

Now a value is to be assigned to the first element of each sub-list, say 10. I tried this: T[:][0] = 10, but it doesn't work. I know that this can be done using a loop, but is there an easier way?


Solution

  • You can use the ternary x if y else z operator in the comprehension:

    T = [[0 if i else 10 for i in range(4)] for _ in range(4)]
    

    And since int is immutable, you can also do:

    T = [[10] + [0] * 3  for _ in range(4)]