Reputation: 5946
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
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 avoidIndexError
exceptions.
Upvotes: 0
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