Hi all!!!
I have some problems with List comprehension in Python.
How can I obtain these two nested list using comprehension?

list1 = [[1,2,3],[4,5,6],[7,8,9]]
list2 = [[1,0,0],[0,1,0],[0,0,1]] (identity matrix)

where list1 and list2 are square matrix of 'n' size

thank you in advance!!!

Recommended Answers

All 3 Replies

for n=3:

list1=[[member*3+1+i for i in range(3)] for member in range(3)]
list2=[[1 if i==member else 0 for i in range(3)] for member in range(3)]

Modifying for any n is left to the user....

And which one you think is better name for variable list2 or identity_matrix? How about square or list1?

wooow... thank you very much slate!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.