Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to split a list into first and rest?

People also ask

How do you split a list?

To split a list in Python, call the len(iterable) method with iterable as a list to find its length and then floor divide the length by 2 using the // operator to find the middle_index of the list.

How do you split items in a list in Python?

To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.

How do you split a string list in Python?

The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace.


first, rest = l[0], l[1:]

Basically the same, except that it's a oneliner. Tuple assigment rocks.

This is a bit longer and less obvious, but generalized for all iterables (instead of being restricted to sliceables):

i = iter(l)
first = next(i) # i.next() in older versions
rest = list(i)

You can do

first = l.pop(0)

and then l will be the rest. It modifies your original list, though, so maybe it’s not what you want.


If l is string typeI would suggest:

first, remainder = l.split(None, maxsplit=1)