Sets are not ordered. So, the sets {1, 2, 3} and {3, 2, 1} are essentially the same.
You must use lists if you want ordered elements.
list1 = [1, 2, 3]
list2 = list1[::-1]
print(list2)
Output is
>>> [3, 2, 1]
EDIT: If you want to use for loop:
list1 = [1, 2, 3]
list2 = []
for x in range(len(list1)-1, -1, -1):
list2.append(list1[x])
print(list2)
The logic of this code is:
The range(a, b, c) function takes 3 arguments : from a to (b-1) with each step of c.
So, we move from the last element (len(list1)-1) of the list1 upto the first element -1 with a step of -1, so that it decreases with each step.
Sets are not ordered. So, the sets {1, 2, 3} and {3, 2, 1} are essentially the same.
You must use lists if you want ordered elements.
list1 = [1, 2, 3]
list2 = list1[::-1]
print(list2)
Output is
>>> [3, 2, 1]
EDIT: If you want to use for loop:
list1 = [1, 2, 3]
list2 = []
for x in range(len(list1)-1, -1, -1):
list2.append(list1[x])
print(list2)
The logic of this code is:
The range(a, b, c) function takes 3 arguments : from a to (b-1) with each step of c.
So, we move from the last element (len(list1)-1) of the list1 upto the first element -1 with a step of -1, so that it decreases with each step.
I think this obeys your rules and prints the set in descending order:
s = {1, 2, 3}
for _ in range(len(s)):
elem = max(s)
s.remove(elem)
print(elem, end=',' if s else '')
# 3,2,1
You could use list slice assignment, which modifies the list in-place:
>>> L = [1, 5, 4, 3, 2, 6]
>>> L[1:5] = L[4:0:-1]
>>> L
[1, 2, 3, 4, 5, 6]
You can reassign the slice of the list to that same slice in reverse
l = [1,5,4,3,2,6]
l[1:5] = l[1:5][::-1]
print(l)
#[1, 2, 3, 4, 5, 6]
The function you're looking for is list comprehensions. These are useful in that you don't have to iterate over a sequence, which is what range and xrange (in 2.x) provide.
str can be iterated over and sliced, much like strings. The only difference is that str elements are immutable.
To your example, say you have a set of strings and you want to iterate over them. No problem - just remember that sets have no inherent ordering to them; they only guarantee that the contents are unique.
myset = set(["first", "second", "third", "fourth", "fifth"])
for i in myset:
print i
...which prints:
second
fifth
fourth
third
first
It's also the case that you can reverse a single string by itself using the step parameter for a sequence type, of which str belongs. You can do that with this:
"this is the song that never ends"[::-1]
...which prints:
'sdne reven taht gnos eht si siht'
try this:
>>> str = 'abcdefghijklmnopqrstuvwxyz'
>>> str[::-1]
'zyxwvutsrqponmlkjihgfedcba'