0

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 ?

Ben Jo
  • 71
  • 1
  • 15
  • To print in without the first letter, replace (index + 1) with (index + 2) and it will exclude the first list element ;) – Aleksei Maide Oct 20 '17 at 12:39

2 Answers2

0
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).

Aleksei Maide
  • 1,845
  • 1
  • 21
  • 23
  • Can you please explain it? – Palash Gupta Oct 20 '17 at 12:24
  • First I got the length of list and then iterated over the range of it while multiplying indeces by -1 to make them negative and access the elements in the "reverse side". – Aleksei Maide Oct 20 '17 at 12:27
  • but i want it till 4 – Palash Gupta Oct 20 '17 at 12:40
  • Just make it (index + 2) It will exclude the first, but I guess you figured it out already ;) – Aleksei Maide Oct 20 '17 at 12:41
  • Beside the fact the answer does not really solve the problem (as expected output is `9,15,7,12,4` and not `9\n15\n7\n12\n4`), this is not the best pythonic approach. Iterating through `range(len(` is unnecessary in this case, as you could change the original iterator by using `reversed(` or even `numbers_list[::-1]`. – FunkySayu Oct 20 '17 at 13:25
  • @FunkySayu I think the dude that asked the question wanted the "Nonpythonic" solution as the question states: for loop and range. – Aleksei Maide Oct 20 '17 at 13:27
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.

FunkySayu
  • 7,641
  • 10
  • 38
  • 61