Seiran
Seiran

Reputation: 126

Pythonic way to create list of prefixes in single line code

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

Answers (1)

niemmi
niemmi

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

Related Questions