Tasos
Tasos

Reputation: 7587

Return sublists of List of lists

Well, I have this example:

mylist = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]

It is a list of lists. I want to keep the first 5 points of each sublist. If it was a simple list I would called mylist[:5] and that's all. Now, the simpliest method I could imagine is to iterate through the mylist and copy the first 5 points of each sublist into a new list.

newlist = []
for i in mylist:
    newlist.append(i[:5])

But what will happen if my list has length 10.000+. Do you know a faster way?

Upvotes: 3

Views: 4460

Answers (4)

Sven Marnach
Sven Marnach

Reputation: 602285

A functional approach:

map(operator.itemgetter(slice(0, 5)), mylist)

Upvotes: 0

Emil Davtyan
Emil Davtyan

Reputation: 14089

You should probably use generators for the inner lists as well, if you are trying to get the process to scale :

g = lambda k: (k[i] for i in range(5))
for x in mylist:
    yield g(x)

Upvotes: 0

user278064
user278064

Reputation: 10180

Another way to achieve it:

return map(lambda lst: lst[:5], mylist)

Upvotes: 0

poke
poke

Reputation: 388113

Well, you could do the same using list comprehension so at least it would get a bit shorter.

return [x[:5] for x in mylist]

Or if making your function a generator instead, you could also yield the individual elements:

for x in mylist:
    yield x[:5]

Upvotes: 9

Related Questions