Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lists: join list by index

Tags:

python

I'd like to join a list into a string by index in Python 3.3. I can do it for items the follow each other, but I would like to access it by index only.

this works:

list = ['A', 'B', 'C', 'D']
partList = "".join(list[1:3])
-> BC

But how can I achieve this (it doesn't work):

list = ['A', 'B', 'C', 'D']
partList = "".join(list[0,3])
-> AD
like image 255
hjstern Avatar asked Oct 18 '25 13:10

hjstern


2 Answers

You can't slice lists into arbitrary chunks using slice notation. Probably your best bet for the general case is to use a list of indices to build a list comprehension.

mylist = ['A', 'B', 'C', 'D'] # the full list
indices = [0, 3] # the indices of myList that you want to extract

# Now build and join a new list comprehension using only those indices.
partList = "".join([e for i, e in enumerate(mylist) if i in indices])
print(partList) # >>> AD

As pointed out in the comments by DSM, if you're concerned with efficiency and you know your list of indices will be "friendly" (that is, it won't have any indices too big for the list you're cutting up), you can use a simpler expression without enumerate:

partList = "".join([mylist[i] for i in indices])
like image 112
Henry Keiter Avatar answered Oct 21 '25 02:10

Henry Keiter


What you are intending to perform is not slicing but selecting.

The closest possibility, I can think of is to use operator.itemgetter

>>> from operator import itemgetter
>>> mylist = ['A', 'B', 'C', 'D']
>>> ''.join(itemgetter(0,3)(mylist))
'AD'

If you need to use a variable, then use a splat operator

index = (0,3)
''.join(itemgetter(*index)(mylist))
like image 42
Abhijit Avatar answered Oct 21 '25 03:10

Abhijit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!