You might already be familiar with some Python functions listed here, but you're sure to discover more useful details about them as you read on.
Function 1: print()
Function
The print()
function is often the first function you learn in Python, and it seems quite basic at first:
age = 21
name = 'Avez'
print("My name is", name, "and I am", age, "years old")
Output:
My name is Avez and I am 21 years old
However, you might not know that you can modify how the print()
function works by using additional arguments. For example, the sep
argument allows you to change the separator between values:
print("My name is", name, "and I am", age, "years old", sep="|")
Output:
My name is|Avez|and I am|21|years old
The sep="|"
makes the print()
function use |
as the delimiter instead of the default whitespace.
Controlling Line Breaks with end
By default, the print()
function adds a newline (\n
) character at the end, moving the output to a new line. However, there may be situations where you want to keep printing on the same line. You can control this behavior using the end
argument:
name = 'Avez'
print("Hello world", end=" ")
print("I am", name)
Output:
Hello world I am Avez
The end=" "
keeps the cursor on the same line and uses double spaces instead of a newline.
By using these additional arguments, you can make the print()
function more flexible and better suited to your formatting needs.
Here’s a refined version of your explanation:
Function 2: help()
The help()
function allows us to access the documentation for any Python function. It essentially prints the docstring of the specified function. Let's see how it works with the built-in print()
function:
help(print)
Output:
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
In the example above, help(print)
shows the detailed description of the print()
function, including its arguments and default values.
Now, let's see how help()
works with a custom function:
def test_func(a, b):
"""
a: value 1
b: value 2
return: int
"""
return a + b
help(test_func)
Output:
Help on function test_func in module __main__:
test_func(a, b)
a: value 1
b: value 2
return: int
Here, help(test_func)
displays the documentation string we provided for test_func
, making it easier to understand the function’s purpose and arguments.
Function 3: range()
The range()
function is commonly used to generate a sequence of numbers, with optional start, stop, and step values. Let’s explore its behavior:
rng = range(10)
print(list(rng))
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The above code generates numbers from 0
to 9
. If you provide a start value, it will generate numbers starting from that value:
rng = range(2, 10)
print(list(rng))
Output:
[2, 3, 4, 5, 6, 7, 8, 9]
Adding a step value controls the increment:
rng = range(2, 10, 2)
print(list(rng))
Output:
[2, 4, 6, 8]
If you print the range object directly without converting it to a list:
rng = range(2, 10, 2)
print(rng)
Output:
range(2, 10, 2)
This is because range()
returns an iterator, which is lazy and memory-efficient. It generates numbers on demand instead of storing them in memory.
Summary:
range()
returns a range object (iterator).list(rng)
converts the range into a list for easier visualization.The range object is lazy and memory-efficient.
Function 4: map()
The map()
function applies a given function to each item in an iterable (e.g., a list). Here's an example:
strings = ["my", "world", "apple", "pear"]
lengths = map(len, strings)
print(list(lengths))
Output:
[2, 5, 5, 4]
Without map()
, we would have to manually loop through the list and apply the len()
function to each string. Using map()
, we can achieve this in a more concise way.
You can also use a custom function with map()
:
def add_s(string):
return string + "s"
lengths = map(add_s, strings)
print(list(lengths))
Output:
['mys', 'worlds', 'apples', 'pears']
Function 5: filter()
The filter()
function is similar to map()
, but it filters items based on a condition. It returns only the items for which the function returns True
. For example:
strings = ["my", "world", "apple", "pear"]
def longer_than_4(string):
return len(string) > 4
filtered = filter(longer_than_4, strings)
print(list(filtered))
Output:
['world', 'apple']
Here, filter()
returns only the strings that have a length greater than 4.
Function 6: sum()
The sum()
function calculates the sum of all elements in an iterable:
numbers = {1, 4.5, 5, 23, 2}
print(sum(numbers))
Output:
35.5
Additionally, sum()
accepts a start
argument, which is the initial value to which the sum will be added:
numbers = {1, 4.5, 5, 23, 2}
print(sum(numbers, start=10))
Output:
45.5
Here, the sum starts from 10, and the elements from the set are added to it.
Function 7: sorted()
The sorted()
function sorts an iterable in ascending order by default. For example:
numbers = {4, 5, 2, 3, -1, 0, 9}
print(sorted(numbers))
Output:
[-1, 0, 2, 3, 4, 5, 9]
To sort in descending order, use the reverse=True
argument:
print(sorted(numbers, reverse=True))
Output:
[9, 5, 4, 3, 2, 0, -1]
You can also sort by a custom key. For example, to sort a list of dictionaries by the "age"
key:
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
{"name": "David", "age": 20},
]
sorted_people = sorted(people, key=lambda person: person["age"])
print(sorted_people)
Output:
[{'name': 'David', 'age': 20}, {'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]
The key
argument sorts the list based on the "age"
value.
Function 8: enumerate()
Next, let's look at the enumerate()
function. Before diving into how it works, let’s see how we can achieve the same functionality without using enumerate()
.
tasks = [
"Write Report",
"Attend Meeting",
"Review Code",
"Submit Timesheet"
]
for index in range(len(tasks)):
task = tasks[index]
print(f"{index+1} {task}")
Output:
1 Write Report
2 Attend Meeting
3 Review Code
4 Submit Timesheet
In this example, we manually access both the index and the task from the list using a for
loop with range(len(tasks))
. Although this works, it’s not the most efficient or readable approach.
Now, let's simplify this with the enumerate()
function, which provides an easier and more Pythonic way to achieve the same result:
tasks = [
"Write Report",
"Attend Meeting",
"Review Code",
"Submit Timesheet"
]
for index, task in enumerate(tasks):
print(f"{index+1} {task}")
Output:
1 Write Report
2 Attend Meeting
3 Review Code
4 Submit Timesheet
The enumerate()
function automatically provides both the index and the corresponding item from the list, making the code cleaner and more readable.
Function 9: zip()
Next, we have the zip()
function. Before diving into its usage, let's first see how we can achieve the same result without using zip()
.
names = ["Alice", "Bob", "Charlie", "David"]
ages = [30, 25, 35, 20]
for idx in range(min(len(names), len(ages))):
name = names[idx]
age = ages[idx]
print(f"{name} is {age} years old}")
In this example, we manually combine the two lists by iterating over them and matching their elements. While this works, it requires more code and effort. With zip()
, we can achieve the same result much more efficiently:
names = ["Alice", "Bob", "Charlie", "David"]
ages = [30, 25, 35, 20]
combined = list(zip(names, ages))
for name, age in combined:
print(f"{name} is {age} years old")
The zip()
function combines the two lists element-wise and makes the code more readable and concise.
Function 10: open()
Next, we have the open()
function. The first argument passed to open()
is the file name you want to access, and the second argument is the mode in which you want to open the file. There are several modes available, but for now, we'll focus on two: 'r'
(read mode) and 'w'
(write mode).
file = open('text.txt', 'w')
file.write("Hello World!")
file.close()
This code creates a file named text.txt
and writes "Hello World!" to it. Note that in 'w'
mode, if the file already exists, it will be overwritten. If the file doesn't exist, a new file will be created. Remember to always call file.close()
to ensure that the file is properly closed and to avoid memory leaks.
Alternatively, we can use the with
statement to automatically handle closing the file, even if an error occurs during the process:
with open('text.txt', 'w') as file:
file.write("Here")
In this case, the file.close()
is automatically called once the block inside the with
statement is completed, so you don’t need to manually close the file. This syntax is considered more Pythonic and safer as it helps prevent potential memory leaks.