[Solved] What’s the most efficient way to split a tuple in two? [closed]


As suggested in comments, you could use itertools.groupby to subdivide the tuple into “not a separator” and “separator” groups and then pick those groups that are not separators. This works for arbitrary numbers of segments, but can also be unpacked into two variables if you know to have exactly two groups.

>>> a = ('a', 'b', 'c', '|', 'd', 'e', 'f', '|', 'g', 'h', 'i')
>>> [tuple(g) for k, g in itertools.groupby(a, key='|'.__eq__) if not k]
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]

This could also be generalized to allow for different separators, using e.g. groupby(a, key='|-'.__contains__).


Regarding comments: The time complexity of this should be O(n), just as when using index, which also is the best you can expect if you don’t know where to split and the tuple is not ordered in any way. Note, however, that groupby presents some overhead which makes this solution about 4-5 times slower than using index tuple slicing. It’s still more versatile and easier applicable for unknown numbers of groups, though.

12

solved What’s the most efficient way to split a tuple in two? [closed]