Simer Simer - 3 months ago 4
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

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.

Comments