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