Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 743
aryst0krat Avatar asked Feb 13 '16 21:02

aryst0krat


People also ask

How do I get the last element in a list?

Get the last item of a list using list. To get the last element of the list using list. pop(), the list. pop() method is used to access the last element of the list.

How do you join values in a list Python?

If you want to concatenate a list of numbers ( int or float ) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join() .

Can you use .join on a list?

We can use python string join() function to join a list of strings. This function takes iterable as argument and List is an interable, so we can use it with List.

How do you join two elements in a list Python?

The most conventional method to concatenate lists in python is by using the concatenation operator(+). The “+” operator can easily join the whole list behind another list and provide you with the new list as the final output as shown in the below example.


1 Answers

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)
like image 62
Daniel Avatar answered Oct 29 '22 16:10

Daniel