Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struggling with slice syntax to join list element of a part of a list

Tags:

python

list

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
like image 640
dawg Avatar asked Mar 07 '12 16:03

dawg


People also ask

What is the correct syntax for list slicing?

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.

How do you join a list of elements in Python?

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.


1 Answers

Use a slice assignment:

l[2:6] = ["".join(l[2:6])]
like image 147
Sven Marnach Avatar answered Sep 16 '22 18:09

Sven Marnach