Simer Simer - 1 year ago 72
Python Question

Join list from specific index

I have a list like below:

ingredients = ['apple','cream','salt','sugar','cider']

I want to join this list to get a string but I want to join from 2nd index till the last one.

to get this :
"salt sugar cider"

Length of list may vary.

Is it possible to do this with join function or I have to do it by looping over elements?

Answer Source

Just slice the list:

>>> l = ['apple', 'cream', 'salt', 'sugar', 'cider']
>>> ' '.join(l[2:])
'salt sugar cider'

We don't specify the end of the slice which means that it would slice to the last element of the list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download