How to flip a string or list in Python, and how to flip a string in python
1. reversed
class reversed(object) | reversed(sequence) -> reverse iterator over values of the sequence | | Return a reverse iterator | | Methods defined here: | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __iter__(...) | x.__iter__() <==> iter(x) | | __length_hint__(...) | Private method returning an estimate of len(list(it)). | | next(...) | x.next() -> the next value, or raise StopIteration | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T
The processed object is an iteratable object, and the returned value is an iterator. Therefore, you can process string list and so on, as shown below:
In [54]: reversed([1,2,3]) Out[54]: <listreverseiterator at 0x7f835810c190>In [55]: reversed('123') Out[55]: <reversed at 0x7f835810c2d0>In [56]: type(reversed('123'))Out[56]: reversedIn [57]: for i in reversed('123'): ....: print i ....: 321
PS: The functions of the built-in _ reversed _ () method of list are similar to those of this method. For details, refer to 2.
2. reverse
Reverse is a built-in method of list, so it can only be used for list, as shown below:
In [62]: l = [1, 2, 3] In [63]: l.reverse()In [64]: lOut[64]: [3, 2, 1]
_ Reversed __()
In [65]: l.__reversed__()Out[65]: <listreverseiterator at 0x7f835810ca90>In [66]: for i in l.__reversed__(): ....: print i ....: 123
3. Slice
The simplest method is to use string and list
In [73]: sOut[73]: 'i am a student.'In [74]: s[::-1]Out[74]: '.tneduts a ma i'In [75]: lOut[75]: [3, 2, 1]In [76]: l[::-1]Out[76]: [1, 2, 3]