Further Python Features (worked examples)
Adapted from https://www.codementor.io/sumit12dec/python-tricks-for-beginners-du107t193, http://www.techbeamers.com/essential-python-tips-tricks-programmers/, http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html, https://pythontips.com/2015/04/19/nifty-python-tricks/
Iterable Objects
Several of these examples involve iterable objects - variables that can be used to access a sequence of values. A simple example is
x=[0, 1, 2, 3, 4] i=iter(x) next(i) next(i) next(i)
Transposing a Matrix
mat = [[1, 2, 3], [4, 5, 6]] list(zip(*mat))
outputs
mat = [[1, 2], [3, 4, [5, 6]]
- Why the *? -
list(zip([1, 2, 3], [4, 5, 6]))
would give the right answer, but mat is a single item. Using * breaks it into a list of items, which is whatzip
needs. - Why use zip? -
zip
takes all the 1st elements of the items given and puts them together, then all the 2nd elements and so on. In this case, 1 and 4 will be put together, then 2 and 5, then 3 and 6. It's like using a real zip, zipping together the corresponding teeth on each side. - Why use list? -
zip
returns an iterable object. If you try to print the output ofzip
you'll get something like<zip object at 0x7f7abed7eac8>
So you need to uselist
Taking a string input
Suppose you want the user to input some numbers to put into a list, and you wanted to do it with one line of code. If you run this
result = map(int ,input().split())
and type
5 6 7 8 print(list(result))
you'll get
[5, 6, 7, 8]
- Why use split? input() gets a string from the user. split() breaks it into strings.
- Why use map?
result = list(input().split())
would output a list of strings
['5', '6', '7', '8']
map(func, *iterables)
make an iterator that runs the functionfunc
using arguments from each of the iterables. In this caseint
converts each string created bysplit
into an integer.
Instead you could use list comprehension
result = (int(x) for x in list(input().split()))
and type
5 6 7 8 print(list(result))
which would get the same output.