Reputation: 1417
Consider the following code
l = [[1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3], [1, 2, 3, 4, 5, 6]]
l1 = []
k = 3
for i in range(len(l)):
l1.append(l[i][:3])
print(l1)
Output is
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
In simple words, I want to trim to a given size, each element of the given list. Can I do it in more compact way?
Upvotes: 0
Views: 41
Reputation: 2801
You can use map
:
l1 = list(map(lambda x: x[:3], l))
Or list comprehension:
l1 = [x[:3] for x in l]
As suggested in the comments.
Upvotes: 3