Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join all except last x in list

I have a list and want to join all except the last 2 entries i.e.

x = ["1", "2", "3", "4"]
print ', '.join(x[from 0 until -3])

Output would then be 1, 2. How could I achieve this?

like image 465
Tristan Ferrua Edwardsson Avatar asked Jun 06 '15 22:06

Tristan Ferrua Edwardsson


People also ask

How do I get all elements of a list except last?

We can use slicing to remove the last element from a list. The idea is to obtain a sublist containing all elements of the list except the last one. Since slice operation returns a new list, we have to assign the new list to the original list. This can be done using the expression l = l[:-1] , where l is your list.

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.

What is string join in python?

Python String join() The string join() method returns a string by joining all the elements of an iterable (list, string, tuple), separated by the given separator.

How does join function work in python?

The Python join() function is used to join all the elements from the iterable and create a string and return it as an output to the user. Python join() returns a new string which is the concatenation of the other strings in the iterable specified.


1 Answers

Use slicing

>>> x = ["1", "2", "3", "4"]
>>> print ', '.join(x[:-2])
1, 2
like image 120
Bhargav Rao Avatar answered Oct 10 '22 14:10

Bhargav Rao