Python Built-In Functions

Are you ready for some Python fun? Let’s get started with built-in functions the ones that make our lives easier and save us time and effort. These are simple tools that can do a lot of heavy lifting when it comes to programming tasks, so let’s take a look at some of them:

1. len() This function returns the number of items in an iterable (like a list or string). For example, if we have a list called “my_list” with 5 elements, calling `len(my_list)` will return 5. Simple as that!

2. max() and min() These functions do exactly what you’d expect: they find the largest and smallest values in an iterable respectively. For example, if we have a list called “numbers” with some random numbers, calling `max(numbers)` will return the highest number in that list.

3. range() This function generates a sequence of numbers based on three arguments: start (inclusive), stop (exclusive), and step (optional). For example, if we want to generate a sequence from 1 to 5 with a step of 2, calling `range(1,6,2)` will return [1,3].

4. round() This function rounds a number to the nearest integer or decimal place based on an optional second argument (the number of decimal places). For example, if we want to round 5.789 to two decimal places, calling `round(5.789,2)` will return 5.79.

5. abs() This function returns the absolute value of a number. For example, if we have a variable called “num” with a negative value, calling `abs(num)` will return that same value but without the minus sign.

6. sorted() This function sorts an iterable in ascending order and returns a new list or tuple (depending on whether you’re sorting a list or tuple). For example, if we have a list called “my_list” with some random numbers, calling `sorted(my_list)` will return a sorted version of that list.

7. reversed() This function returns a reverse iterator for an iterable (like a list or string), which can be used in a for loop to iterate over the elements in reverse order. For example, if we have a list called “my_list” with some random numbers, calling `reversed(my_list)` will return a reversed iterator that we can use like this:

# Define a list of numbers
my_list = [1, 2, 3, 4, 5]

# Create a reversed iterator for the list
reversed_list = reversed(my_list) # reversed() returns a reversed iterator for the given iterable

# Iterate over the elements in reverse order using a for loop
for num in reversed_list: # reversed_list contains the elements of my_list in reverse order
    print(num) # Print each element in the reversed list

# Output:
# 5
# 4
# 3
# 2
# 1

These are just a few of the many built-in functions available to us in Python. So next time you find yourself struggling with a task, remember: there’s probably a built-in function for that!

SICORPS