concept new list in category python

appears as: new list
Tiny Python Projects: Learn coding and testing with puzzles and games

This is an excerpt from Manning's book Tiny Python Projects: Learn coding and testing with puzzles and games.

The reversed() function works a bit differently:

>>> reversed(items)
<list_reverseiterator object at 0x10e012ef0>

I bet you were expecting to see a new list with the items in reverse. This is an example of a lazy function in Python. The process of reversing a list might take a while, so Python is showing that it has generated an iterator object that will provide the reversed list when we actually need the elements.

An easier way to write this would be to use the dict.items() method, which will return the contents of the dictionary as a new list containing each key/value pair:

A shorter solution uses a list comprehension, which is basically a one-line for loop inside square brackets ([]) that results in a new list (see figure 4.8).

def main():
    args = get_args()
    jumper = {'1': '9', '2': '8', '3': '7', '4': '6', '5': '0',
              '6': '4', '7': '3', '8': '2', '9': '1', '0': '5'}
    print(''.join([jumper.get(char, char) for char in args.text]))
Figure 4.8 A list comprehension will generate a new list with the results of iterating with a for statement.