disruptive
disruptive

Reputation: 5946

Pythonic way to convert two adjacent list elements to a tuple and preserve rest of list

I'm looking for an elegant way to convert

lst = [A, B, C, D, E..]

to

lst = [A, B, (C, D), E]

so given that I want to do this on index 2 and 3 but preserve the list. Is there an elegant way to perform this? I was looking with a lambda function but I did not see it.

Upvotes: 1

Views: 70

Answers (2)

martineau
martineau

Reputation: 123423

You could use:

lst[2] = lst[2], lst.pop(3)

or more generally:

lst[i] = lst[i], lst.pop(i+1)

However you must insure that both indices are valid in avoidIndexErrorexceptions.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121486

Just alter in-place:

lst[2:4] = [tuple(lst[2:4])]

The slice assignment ensures we are replacing the old elements with the contents of the list on the right-hand side of the assignment, which contains just the one tuple.

Demo:

>>> lst = ['A', 'B', 'C', 'D', 'E']
>>> lst[2:4] = [tuple(lst[2:4])]
>>> lst
['A', 'B', ('C', 'D'), 'E']

Upvotes: 5

Related Questions