How would I write this for loop as a list comprehention?
This is the list:
table = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
I want to delete row 4 and 5
for row in table: del row[3:]
I did try this but it just gives me a syntax error
table2 = [del row[5:] for row in table]
Any idea how to do that with a list comprehension?
Advertisement
Answer
You can slice the list upto index 3:
>>> table = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]] >>> table2 = [i[:3] for i in table] >>> table2 [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
If that is what you want.