Chapter 4

How do we retrieve one element from a list? How do we retrieve the last element of the list without computing its length explicitly?

To retrieve any element from a list, we can pass its index (order, starting with zero) in square brackets: mylist[0] will get the first element. Similarly, negative indices will return elements in reverse order—mylist[-1] will get the last element, no matter how many of them are stored.

How do we get all the elements of a list – except the first one and the last one – in reverse order?

For that, we can use slicing. In a slice, the first number represents the start, the second number represents the end, and the third one represents the step. A negative number will lead to the reverse order. Since we're using all three values and the step is negative, we need to swap the start and end values. Since the start is already included but the end isn't, we'll have to shift indices accordingly:

>>> mylist = [1,2,3,4,5]
>>> mylist[-2:0:-1]
[4,3,2]

Alternatively, we can do that in two steps:

>>> mylist[1: -1][::-1]
[4,3,2]

How do we merge two dictionaries, and what happens if some of the keys are the same in both of them?

The best way to merge two dictionaries is to update one with another. In this case, overlapping values will be overwritten by the values of the second dictionary:

>>> D1, D2 = {'a':1, 'b':2} {'b':3, 'c':4}
>>> D1.update(D2)
>>> D1
{'a':1, 'b':3, 'c':4}

What is the best data structure to check for membership?

The best structure to check for membership is a set.

Can we get the last element of the generator without getting all the others?

No, it is not feasible by definition—to get the last value in a generator, you have to go over all previous ones—and besides, generators can be infinite.

How do we combine elements from triplets into three arrays of N, one by one?

For that, there is the zip function. Consider the following example (N is equal to 4):

>>> arrays = ((1,2,3), (4,5,6), (7,8,9), (10,11,12))
>>> list(zip(*arrays)) # list is needed for printing
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]

What is the short way of generating a list of specific dictionary properties – which are retrieved from a list of dictionaries – if a certain other property of each dictionary is in the set?

Here, we need to execute multiple operations at once – filter dictionaries and get a specific value out of them. The shortest way to do that is via one-liners:

>>> dicts = [{'a':1, 'keep':False},
{'a':2, 'keep':True},
{'a':3, 'keep':True}]

>>> [D['a'] for D in dicts if D['keep']]
[2,3]

That's it!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.43.192