DdD
DdD

Reputation: 612

How to change the value of a "column" of a nested list in python?

In python 3, I have a nested list

my_list= [
   [2,2,2,2],
   [3,3,3,3],
   [4,4,4,4]
]

and I'd like to change all the values of the second column to 0, to get

my_list= [
   [2,0,2,2],
   [3,0,3,3],
   [4,0,4,4]
]

Now, what I can do is

for i in range(len(my_list)):
    my_list[i][1] = 0

but it doesn't seem to be very "pythonic", am I correct? Is there a smarter way of doing it without using the length of the array?

In Numpy I could use my_list[:,2]=0.

Upvotes: 1

Views: 2983

Answers (2)

F1Rumors
F1Rumors

Reputation: 948

Interesting. A more generic solution seems to be useful here. What if you want to replace that column with another column ... that would be more like:

def replaceColumn(listOfLists, n, column):
    ''' Replace the "n"th column of the list of lists "table" source '''
    # Rotate the table...
    t = list(zip(*listOfLists))
    # Replace the (now) row
    t[n] = column
    # Rotate and return the table...
    return list(zip(*t))

Then the solution is more like:

replaceColumns(my_list, [0]*len(my_list), 1)

There is a side effect though: the rows end up as tuples!

Upvotes: 0

Abhinav Upadhyay
Abhinav Upadhyay

Reputation: 2585

A more pythonic way would be the following:

In [9]: for inner_list in my_list:
   ...:     inner_list[1] = 0
   ...:     

In [10]: my_list
Out[10]: [[2, 0, 2, 2], [3, 0, 3, 3], [4, 0, 4, 4]]

In Python when looping over lists or collections, you don't need to use range(len(my_list)), the for loop knows when to stop.

Upvotes: 4

Related Questions