TAGS :Viewed: 8 - Published at: a few seconds ago

[ Join last element in list ]

I've been searching google and this site for an answer to this to no avail, with a few different search terms. So if the question has already been answered, I'd love to be pointed to it.


I'm trying to join a range of elements of a list, including the last element of the list. Here's my test code:

inp = ['1','2','3','4']
test = '_'.join(inp[0:2])
test2 = '_'.join(inp[2:-1])

print(test + ' & ' + test2)

I know the range won't include the last element of the list, so this just give me 3 for test2, but if I use 0 instead of -1 in an attempt to get it to include the last element by looping back around, it returns nothing instead.


I'm very new to coding still, so it wouldn't surprise me if there's an easier way of doing this altogether. I'd be happy to know if this is solvable but equally happy for a different solution. Essentially I'm pulling the first two items in a list out to check them against an object name, and having the rest of the list - no specific number of elements - be a second variable.

I assume I could do something like pop the first two elements out of the list and into their own, and then join that list and the truncated original one without using ranges. But if the check fails I need to use the original list again, so I would have to make a copy of the list as well. If at all feasible, it would be nice to do in with less code than that would take?

Answer 1


To get the list including the last element, leave the end out:

inp = ['1','2','3','4']
test = '_'.join(inp[:2])
test2 = '_'.join(inp[2:])

print(test + ' & ' + test2)

Answer 2


You can use a nested join:

>>> ' & '.join(['_'.join(inp[i:j]) for i, j in zip([0, 2], [2, None])])
'1_2 & 3_4'

or a simpler solution:

>>> ' & '.join(["_".join(inp[:2]), "_".join(inp[2:])])
'1_2 & 3_4'