Attach the last item in the list

I searched google and this site to answer this question to no avail, with several different search terms. Therefore, if the question has already been answered, I would like to be pointed out.


I am trying to join a number of list items, including the last list item. Here is my test code:

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

I know that the range will not contain the last element of the list, so that just give me 3 for test2, but if I use 0 instead of -1, I will try to include it in the last element, looping back around, returns nothing.


I am very new to coding, so it wouldn't surprise me if there was an easier way to do this at all. I would be glad to know if this is permitted, but equally glad to have another solution. Essentially, I pull out the first two elements in the list to check them for the name of the object, and the rest of the list - an undefined number of elements - will be the second variable.

I suppose I could do something like pop the first first elements from the list and into their own, and then join this list and the truncated original without using ranges. But if the check fails, I need to use the original list again, so I also have to make a copy of the list. If at all possible, it would be nice to do this with less code, what will it take?

+6
source share
2 answers

To get a list including the last item, leave the end:

 inp = ['1','2','3','4'] test = '_'.join(inp[:2]) test2 = '_'.join(inp[2:]) print(test + ' & ' + test2) 
+5
source

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 simpler solution:

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

All Articles