I have the following list on python:
items = [5,4,12,7,15,9]
and I want to print in this form:
9,15,7,12,4
How can I do that ?
I have the following list on python:
items = [5,4,12,7,15,9]
and I want to print in this form:
9,15,7,12,4
How can I do that ?
numbers_list = [5,4,12,7,15,9]
for index in range(len(numbers_list)):
print(numbers_list[(index + 1) * - 1])
Not sure if it's very "Pythonic"
As the list indeces are being negated you can access the elements in the reverse order.
Last index in a Python is list [-1] and so on, till the first one being list length -1 (Plus one in this case to get the negative number closer to 0).
Using reversed
and str.join
:
numbers = [5, 4, 12, 7, 15, 9]
print(",".join(str(n) for n in reversed(numbers))) # 9,15,7,12,4,5
str.join
is by far better than building your own string using mystring += "something"
in terms of performances. How slow is Python's string concatenation vs. str.join? provides interesting insights about this.
I could also write a list comprehension to build an intermediate list like this:
reversed_string = [str(n) for n in reversed(numbers)]
print(",".join(reversed_string))
but writing list comprehension implies we store in-memory twice the list (the original one and the "strigified" one). Using a generator will dynamically compute the elements for str.join
, somewhat the same way a classic iterator would do.