Re: Splitting a list

Discussion in 'Python' started by Jeff Epler, Aug 31, 2004.

1. Jeff EplerGuest

Here's my version as a generator function:
def split(it, elem):
l = []
for i in it:
if i == elem:
yield l
l = []
else:
l.append(i)
yield l

>>> list(split(" a b c ", " "))

[[], ['a'], ['b'], ['c'], []]
>>> " a b c ".split(" ")

['', 'a', 'b', 'c', '']
>>> l = [1,2,3,-1,4,5,-1,8,9]
>>> list(split(l, -1))

[[1, 2, 3], [4, 5], [8, 9]]

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFBNIcZJd01MZaTXX0RAj0rAKClAYICBN0jWfcGZFxZGLEnZZfaiACdFlHS
E9q0hAi2oS9BMpriHM4/m0w=
=w4T2
-----END PGP SIGNATURE-----

Jeff Epler, Aug 31, 2004

2. Peter OttenGuest

Jeff Epler wrote:

> Here's my version as a generator function:
> def split(it, elem):
> l = []
> for i in it:
> if i == elem:
> yield l
> l = []
> else:
> l.append(i)
> yield l
>

A clean algorithm, but it has one corner case that strikes me as
counterintuitive:

>>> list(split([], None))

[[]]

I would prefer [], so I cross-checked with str.split():

>>> "".split()

[]
>>> "".split("x")

['']

Strange. Is that by design or by accident?

Peter

Peter Otten, Aug 31, 2004