Built-ins are a somewhat overlooked part of Python. You use them every day, but there are a number of them that get overlooked or just aren’t used to their full potential. This article won’t be covering all the built-ins in Python, but will focus on the ones that you probably don’t use every day.
any()
The any() built-in accepts an iterable and will return True is any element in said iterable is True. Let’s take a look at an example:
>>> any([0,0,0,1]) True
In this case, you pass any() a list of zeros and a one. Because there’s a one there, it returns True. You might be wondering when you would ever use this built-in. I did too at first. An example that cropped up in one of my jobs involved a very complex user interface where I had to test various pieces of functionality. One of the items that I needed to test was if a certain list of widgets had been shown or enabled when they shouldn’t be. The any() built-in was very useful for that.
Here’s an example that kind of demonstrates what I’m talking about, although it’s not the actual code I used:
>>> widget_one = '' >>> widget_two = '' >>> widget_three = 'button' >>> widgets_exist = any([widget_one, widget_two, widget_three]) >>> widgets_exist True
In this example, you would query the user interface and ask it if widgets one through three existed and put the responses into a list. If any of them returned True, then it would raise an error.
You might want to check out Python’s all built-in as it has similar functionality except that it will only return True if every single item in the iterable is True.
enumerate()
Have you ever needed to loop over a list and also needed to know where in the list you were at? You could add a counter that you increment as you loop, or you could use Python’s built-in enumerate() function! Let’s try it out on a string!
>>> my_string = 'abcdefg' >>> for pos, letter in enumerate(my_string): ... print (pos, letter) ... 0 a 1 b 2 c 3 d 4 e 5 f 6 g
In this example, you have a 6-letter string. In your loop, you wrap the string in a call to enumerate. This returns the position of each item in the iterable as well as the value. You print them both out so you can see what’s going on. I personally have found many use cases for enumerate(). I’m sure you will too.
eval()
The eval() built-in is fairly controversial in the Python community. The reason for this is that eval accepts strings and basically runs them. If you were to allow users to input any string to be parsed and evaluated by eval, then you just created a major security breach. However, if the code that uses eval cannot be interacted with by the user and only by the developer, then it is okay to use. Some will argue that it’s still not safe, but if you have a rogue developer, they can do a lot more harm doing other things than using eval.
Let’s take a look at a simple example:
>>> var = 10 >>> source = 'var * 2' >>> eval(source) 20
Here, you create two variables. The first is assigned the integer 10. The second has a string that has the same letters as the variable you just defined and it looks like you’re going to multiply it by two. However, it’s just a string so it doesn’t do anything. But with eval(), you can make it do something! You can see it in action on the very next line where you pass the string into eval and you get a result. This is why people think that eval can be dangerous.
There is another built-in function called exec() which supports the dynamic execution of Python code. It’s a somewhat “dangerous” built-in too, but it doesn’t have the bad reputation that eval() does. It’s a neat little tool, but use it with caution.
filter()
The filter() built-in function will take a function and an iterable and return an iterator for those elements within the iterable for which the passed-in function returns True. That statement sounds a bit confusing to read, so let’s look at an example:
>>> def less_than_ten(x): ... return x < 10 ... >>> my_list = [1, 2, 3, 10, 11, 12] >>> for item in filter(less_than_ten, my_list): ... print(item) ... 1 2 3
Here you create a simple function that tests if the integer you pass to it is less than 10. If it is, then it returns True; otherwise, it returns False. Next you create a list of 6 integers with half of them being less than 10. Finally, you use filter() to filter out the integers that are greater than ten and only print the ones that are less.
You may recall that the itertools module has a function that is similar to this one called filterfalse. That function is the opposite of this one and only returns elements of the iterable when the function returns False.
map()
The map() built-in also takes a function and an iterable and returns an iterator that applies the function to each item in the iterable. Let’s take a look at a simple example:
>>> def doubler(x): ... return x * 2 ... >>> my_list = [1, 2, 3, 4, 5] >>> for item in map(doubler, my_list): ... print(item) ... 2 4 6 8 10
The first thing you define is a function that will double whatever is passed to it. Next, you have a list of integers, 1-5. Finally, you create a for loop that loops over the iterator that is returned when you call map with our function and list. The code inside the loop will print out the results.
The map and filter functions basically duplicate the features of generator expressions in Python 3. In Python 2, they duplicate the functionality of list comprehensions. You could shorten the code above a bit and make it return a list like so:
>>> list(map(doubler, my_list)) [2, 4, 6, 8, 10]
But you can do the same thing with a list comprehension:
>>> [doubler(x) for x in my_list] [2, 4, 6, 8, 10]
So it’s really up to you which you want to use.
zip()
The zip() built-in takes a series of iterables and aggregates the elements from each of them. Let’s see what that means:
>>> keys = ['x', 'y', 'z'] >>> values = [5, 6, 7] >>> zip(keys, values) <zip object at 0x7fc76575a548> >>> list(zip(keys, values)) [('x', 5), ('y', 6), ('z', 7)]
In this example, you have two lists of equal size. Next, you zip them together with the zip function. This just returns a zip object, so you wrap that in a call to the list built-in to see what the result is. You end up with a list of tuples. You can see here that zip matched up the items in each list by position and put them into tuples.
One of the most popular use cases for zip() is to take two lists and turn them into a dictionary:
>>> keys = ['x', 'y', 'z'] >>> values = [5, 6, 7] >>> my_dict = dict(zip(keys, values)) >>> my_dict {'x': 5, 'y': 6, 'z': 7}
When you pass a series of tuples to Python’s dict() built-in, it will create a dictionary as you can see above. I’ve used this technique from time to time in my own code.
Wrapping Up
While this was a brief tour, I hope it gave you a good idea of just how much power Python’s built-ins give you. There are many others that you use every day, such as list, dict and dir. The built-in functions that you learned about in this chapter probably won’t get used every day, but they can be extremely helpful in certain situations. I am actually devoting an entire chapter to a special built-in known as super, which you can read about later on in the book. Have fun with these and be sure to look up the documentation to see what other jewels exist.
Related Reading
- Python 101 – Learning about dictionaries
- Python 101 – Learning about lists
- Python 101 – Learning about tuples
The post An Intro to Python’s Built-in Functions appeared first on Mouse Vs Python.