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?
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.
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.
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.
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.
Use slicing
>>> x = ["1", "2", "3", "4"]
>>> print ', '.join(x[:-2])
1, 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With