I have a content of strings and I have to reverse the order using python. the content is
- Python
- Java
- microsoft
I have a content of strings and I have to reverse the order using python. the content is
If you want a new list:
a = ["Python", "Java", "Microsoft"]
b = a[::-1]
# b is now ["Microsoft", "Java", "Python"]
or
a = ["Python", "Java", "Microsoft"]
b = list(reversed(a))
# b is now ["Microsoft", "Java", "Python"]
If you want to modify an existing list:
a = ["Python", "Java", "Microsoft"]
a.reverse()
# a is now ["Microsoft", "Java", "Python"]
If you want a list where each of the individual strings has had its characters reversed:
a = ["Python", "Java", "Microsoft"]
b = [x[::-1] for x in a]
# b is now ["nohtyP", "avaJ", "tfosorciM"]
The reason why using slice notation with a[::-1]
returns a sequence that is the reverse of a
is because slice notation works like this:
sequence[start:end:step]
since you specify step
to be -1, that means that it works backwards through the sequence one by one, which is in effect the reverse of the sequence. (start
and end
being omitted uses their default values, i.e. the entire sequence.)
>>> l = ["Microsoft", "Java", "Python"]
>>> l.reverse()
>>> l
['Python', 'Java', 'Microsoft']
>>>
the most comprehensible option for sequences is to use "reversed", but the result is always a list, so for a string you could either use it and convert it to a string again by joining the elements, or use a slice with negative index (this later being more efficient, I guess):
s = "abcd"
reversed(s) #-> ['d','c','b','a']
"".join(_) #-> 'dcba'
#or
s[::-1] #-> 'dcba'