7/15 reverse


#1

I have a question regards the following code I wrote:
def reverse(text):
texts = []
for i in text:
texts.append(text[len(text) - (i[] - 1)])
return ‘’.join(texts)

Python obviously gave me the invalid syntax because i[] makes no sense. What I’m wondering, is there some simple syntax to get the i’th index when iterating over i?

I solved it another way but I’m just curious


#2

The text.index(i) method will give you the index of i in text.

Eg

>>> x = "string"
>>> for i in x:
	print (x[len(x) - x.index(i) - 1])

	
g
n
i
r
t
s
>>> 

#3

Noo don’t do that. Might not be the same location and inappropriate time complexity


#4

I’d have to agree. Was only attempting to answer the direct question, re index.


#5

The for loop does not care about the positions of values, it only does iteration (the logic of which is handled by the value being iterated through, in this case a list), indeed, some iterable values may not even have positions for the values iterated over

You would therefore need to obtain the index separately, typically by creating an iterable which either produces only indexes and use that to access the values, or one that produces pairs of indexes and values from your list (the enumerate function creates such iterables)


#6

I see, thank you for clarifying. I just got a deeper understanding of looping :smiley:


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.