Reputation: 126
Given: a list, for example [1,2,"hello","world"]
Need to: create list of lists with all the prefixes,
for example the output will be: [[], [1], [1, 2], [1, 2, "hello"], [1, 2, "hello", "world"]]
Problem: the function body must contain only single line code.
I don't have any problem to do this with regular way (loops, etc..) but cant figure out how to do only with single line.
Upvotes: 0
Views: 306
Reputation: 17263
You can use range
to iterate indexes within list comprehension and use slicing to create the prefixes:
>>> l = [1,2,"hello","world"]
>>> [l[:i] for i in range(len(l) + 1)]
[[], [1], [1, 2], [1, 2, 'hello'], [1, 2, 'hello', 'world']]
Upvotes: 4