Suppose I have a simple Python list like this:
>>> l=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Now suppose I want to combine l[2:6]
to a single element like this:
>>> l
['0', '1', '2345', '6', '7', '8', '9']
I am able to do it in steps into a new list, like this:
>>> l2=l[0:2]
>>> l2.append(''.join(l[2:6]))
>>> l2.extend(l[6:])
>>> l2
['0', '1', '2345', '6', '7', '8', '9']
Is there a way (that I am missing) to do this more simply and in place on the original list l
?
Edit
As usual, Sven Marnach had the perfect instant answer:
l[2:6] = ["".join(l[2:6])]
I had tried:
l[2:6] = "".join(l[2:6])
But without the braces, the string produced by the join was then treated as an iterable placing each character back in the list and reversing the join!
Consider:
>>> l=['abc','def','ghk','lmn','opq']
>>> l[1:3]=[''.join(l[1:3])]
>>> l
['abc', 'defghk', 'lmn', 'opq'] #correct
>>> l=['abc','def','ghk','lmn','opq']
>>> l[1:3]=''.join(l[1:3])
>>> l
['abc', 'd', 'e', 'f', 'g', 'h', 'k', 'lmn', 'opq'] #not correct
The format for list slicing is [start:stop:step]. start is the index of the list where slicing starts. stop is the index of the list where slicing ends. step allows you to select nth item within the range start to stop.
Using join() method to concatenate items in a list to a single string. The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.
Use a slice assignment:
l[2:6] = ["".join(l[2:6])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With