Harvey
Harvey

Reputation: 5821

Is there a single call method of splitting a list (iterable) into two parts?

Is there a built-in or Pythonic way to do this? Or maybe my question should be: Is there a better way to write the dictionary comprehension example at the end of this question?

def split_list(list, index):
    return list[:index], list[index:]

I find myself needing to do this in list comprehensions where I get lists from some generator and want to split the lists into two pieces. For example, a text file like the following:

txt_file = """key1 value value value value
key2 value value value value
"""
import io
{k:v
 for line in io.StringIO(txt_file)
 for items in (line.strip().split(),)
 for k, v in ((items[0], items[1:]),)}

Output:

{'key1': ['value', 'value', 'value', 'value'],
 'key2': ['value', 'value', 'value', 'value']}

Upvotes: 2

Views: 45

Answers (1)

glibdud
glibdud

Reputation: 7860

The only comment I'd make is that there's no real reason for your last for in that comprehension.

{items[0]:items[1:]
 for line in io.StringIO(txt_file)
 for items in (line.strip().split(),)}

And I don't know of a "better" way to split a list in two.

Upvotes: 1

Related Questions