8 Things You Must Know in Python (2023)

Introduction

In this tutorial, we will look at 8 things you must know in Python (2023).  Python provides a wide range of built-in functions that are readily available for use without requiring you to import external modules or libraries. These built-in functions cover various aspects of programming, including data manipulation, control flow, I/O and more. In this tutorial, we will cover some of the most widely used built-in functions and discuss it’s usage along with examples.

 

 

8 Things You Must Know in Python (2023)

8 Things You Must Know in Python (2023)

Also read: How to Install Kali Linux 2023.3 on VirtualBox: [7 Simple Steps]

In the next section, we will cover 8 most important and most widely used Python’s built-in functions. These are all(), any(), enumerate(), zip(), reversed(), min(), max() and sorted(). Before going ahead with discussion on these functions, you must understand about iterable and sequence in Python. So let’s get started.

Iterable:  In Python, an iterable is an object that can be looped over, meaning you can iterate through its elements one at a time. Iterables include data structures like lists, tuples, strings, dictionaries, sets and more. We use for loop to iterate over the elements of an iterable.

Sequence:  A sequence is a specific type of iterable where elements are sorted in a specific  order and can be accessed by an index. Sequences include data structures like lists, tuples and strings.  Example of things that are iterables but not sequence are dictionaries, sets, files, generators. Elements in sequence have a definite position and can be retrieved by their index in the sequence, Index starts from 0. We can also use slicing to extract  a portion of a sequence.

 

Also read: How to Build Port Scanner using Python: [2 Easy Examples]

1. Python all()  function

Python has a built-in function called all() that returns true if all the elements are true i.e they are non-empty or non-zero. As we discussed earlier,  Iterable is anything that you can loop over using a for loop. Examples, lists, tuples, strings, sets and dictionaries. Below is the example to demonstrate the all() function.

Syntax of all():
all(
condition(item)
for item in iterable
)

Example-1:

def valid_range(abc):

    '''Receives (a, b, c) tuple, Checks if each abc is within (0, 255, 255)'''
    valid = [
        0 <= val <= 255
        for val in abc
    ]

    return all(
        0 <= val <= 255
        for val in abc
    )

assert valid_range((25, 5, 225)) == True
assert valid_range((25, 500, 25)) == False
assert valid_range((125, 25, 45)) == True
assert valid_range((625, 5, 225)) == False
assert valid_range((425, 155, 325)) == False
print('All tests are Passed...')
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-all.py
All tests are Passed...

 

2. Python any() function

Python has a built-in function called any() which returns true if any of the items are true i.e they are non-empty or non-zero. Below is the example to demonstrate the any() function.

 

Syntax of any():
any(
    condition(item)
    for item in iterable
)

 

Example-2:
def anyFunc(input):

    return any(char.isdigit()
        for char in input
    )

assert anyFunc("This is string input") == False
assert anyFunc("This is alpha123 input") == True
assert anyFunc("123456")
print("All tests are passes..")
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-any.py
All tests are passes..

 

3. Python enumerate() function

In Python, enumerate() function is used to iterate over an iterable (e.g list, tuple or string) while keeping track of the index of each element within the iterable. It returns an iterator that generates pairs of(index, element) tuples as you iterate through the elements of the iterable.  Below is the example to demonstrate the enumerate() function.

Syntax of enumerate():
enumerate(sequence, start=0)

Example-3:

cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']

for element in enumerate(cars, start=1):
    print(element)
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-enumerate.py
(1, 'Lamborghini')
(2, 'Porsche')
(3, 'Tesla')
(4, 'Honda')
(5, 'Jaguar')
(6, 'Nissan')

 

We can also split out the index and elements using enumerate as shown below.

cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']

for index, element in enumerate(cars, start=1):
    print(f"{index}. {element}")
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-enumerate.py
1. Lamborghini
2. Porsche
3. Tesla
4. Honda
5. Jaguar
6. Nissan

 

4. Python zip() function

In Python,  zip()  function is used to combine two or more iterables (e.g lists, tuples) element-wise into a single iterable. It pairs up the elements from each input iterable based on their positions and create an iterator of tuples containing elements from the corresponding positions in the input itearbles.

Syntax of zip():
zip(iterable1, iterable2, …)

Example-4:

cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']
owners = ['Bobby', 'Alexander', 'John', 'Hailey', 'Rocky', 'Brian']

for car, owner in zip(cars, owners):
    print(f"Owner of the car {car} is: {owner}")
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-zip.py
Owner of the car Lamborghini is: Bobby
Owner of the car Porsche is: Alexander
Owner of the car Tesla is: John
Owner of the car Honda is: Hailey
Owner of the car Jaguar is: Rocky
Owner of the car Nissan is: Brian

So the zip function makes an iterator that aggregates elements from each of the iterables. If let’s say in any of the above two list, the number of elements does not match, zip function will stop. So it will print the output till the total number of elements in both the list match. Below is the demonstration:

 

cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']
owners = ['Bobby', 'Alexander', 'John', 'Hailey']

for car, owner in zip(cars, owners):
    print(f"Owner of the car {car} is: {owner}")
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-zip.py
Owner of the car Lamborghini is: Bobby
Owner of the car Porsche is: Alexander
Owner of the car Tesla is: John
Owner of the car Honda is: Hailey

 

As you notice in the above code, i have deleted last two elements from the owners list, so zip will print the output till ‘Hailey’ element as this is the last element in owners list.
But what if we want the zip() function to print all the output by doing something for he missing elements?. In such case, we can use zip_longest from the Python’s itertools package. This function provides an extra flag ‘fillvalue=”<value>”‘ using which we can assign any value for the missing elements in the list. Below is the demonstration:
from itertools import zip_longest

cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']
owners = ['Bobby', 'Alexander', 'John', 'Hailey']

for car, owner in zip_longest(cars, owners, fillvalue="Missing"):
    print(f"Owner of the car {car} is: {owner}")
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-zip.py
Owner of the car Lamborghini is: Bobby
Owner of the car Porsche is: Alexander
Owner of the car Tesla is: John
Owner of the car Honda is: Hailey
Owner of the car Jaguar is: Missing
Owner of the car Nissan is: Missing

 

5. Python reversed() function

Every list in Python has a built-in reverse() function. So you can reverse the contents of the list objects inplace, meaning it will directly modify the original list object. They are different ways to reverse a list, each has its own impact. Let’s look at below example.

Syntax of reversed():
reversed(sequence)

Example-5:

cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']

cars.reverse()
print(cars)
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-reversed.py
['Nissan', 'Jaguar', 'Honda', 'Tesla', 'Porsche', 'Lamborghini']

 

As you notice, it has modified the original list which sometime might become downside of using the reverse() function. TO overcome this, we can use reversed() function. So reversed()  function will not modify the original list inplace nor will it create a copy of list(which happens when we use slicing to reverse the string), it will return an iterator of the reverse items instead. Below is the demonstration
cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']

for car in reversed(cars):
    print(car)

print("Orinal list: ", cars)
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-reversed.py
Nissan
Jaguar
Honda
Tesla
Porsche
Lamborghini
Orinal list: ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']
As you notice, it does not modify the original list instead only returns the iterable of reversed elements.

 

Odd case :
strings and tuples in Python are immutable so reverse() function does not work on them because it directly modifies the original list which is not allowed for immutable type. For such data type, we can either use slicing (not memory efficient) or reversed() function(memory efficient). Below is the demonstration.

 

Tuple data type will throw error
'''tuple type'''
cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']

carTuple = tuple(cars)
carTuple.reverse()
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-reversed.py
Traceback (most recent call last):
File "PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects>\func-reversed.py", line 4, in <module>
carTuple.reverse()
AttributeError: 'tuple' object has no attribute 'reverse'

 

String data type will throw error
'''string type'''

car = 'Maruti'
car.reverse()
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-reversed.py
Traceback (most recent call last):
File "PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects>\func-reversed.py", line 4, in <module>
car.reverse()
AttributeError: 'str' object has no attribute 'reverse'

 

Use reversed() function
'''tuple type'''
cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']

for car in reversed(tuple(cars)):
    print(car)

'''string type'''
car = 'Maruti'

string = "".join(reversed(car))
print(string)
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-reversed.py
Nissan
Jaguar
Honda
Tesla
Porsche
Lamborghini
ituraM

 

6. Python min() function

In Python, min() function returns the smallest element in the iterable or the smallest of two or more arguments. Below is the example to demonstrate the min() function.

Syntax of min()
min(iterable, *, key=None)

Example-6:

price = [51_00_000, 22_00_00, 62_50_000, 94_00_00, 80_00_00]
print(min(price))
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-min.py
220000

In the above code, since 22_00_00 is the smallest element of all, it is returned as output.

 

7. Python max() function

In Python, max() function returns the largest element in the iterable or the largest of two or more arguments. Below is the example to demonstrate the max() function.

Syntax of max()
max(iterable, *, key=None)

Example-7:

cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']
print(max(cars))
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-max.py
Tesla
In the above code, all the elements are type string. so min will compare the characters of each element an which ever element has the highest ASCII value, it will return that element as output.

 

Now what if we want to print the car which has the lowest price? In this case, we can utilize collection of functions which we have already seen above and get the output. Below is the demonstration
cars = ['Lamborghini', 'Porsche', 'Tesla', 'Honda', 'Jaguar', 'Nissan']
prices = [51_00_000, 22_00_00, 62_50_000, 94_00_00, 80_00_00, 77_00_000]

def carWithLowestPrice(pair):
    car, price = pair
    return price

print(f"Lowest priced car: {min(zip(cars, prices), key=carWithLowestPrice)}")
print(f"Highest priced car: {max(zip(cars, prices), key=carWithLowestPrice)}")
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-min-max.py
Lowest priced car: ('Porsche', 220000)
Highest priced car: ('Tesla', 6250000)
In the above code, we have used zip function to loop over two list. After that we have passed zip to min() and max() functions to find the minimum maximum priced car respectively.

 

8. Python sorted() function

In Python, just like the min() and max() functions, all of the values that we give to sorted need to be orderable. Below is the example to demonstrate sorted() function.

 

Syntax of sorted()
sorted(iterable, /, *, key=None, reverse=False)

 

Example-8:
class Car:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __repr__(self):
        return f"Car({self.name}, {self.price})"


car_list = [

    Car('Lamborghini', 51_00_000),
    Car('Porsche', 22_00_00),
    Car('Tesla', 62_50_000),
    Car('Honda', 94_00_00),
    Car('Jaguar', 80_00_00),
    Car('Nissan', 77_00_000),
]

print(sorted(car_list, key=lambda x: x.price))
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\python_projects> python .\func-sorted.py
[Car(Porsche, 220000), Car(Jaguar, 800000), Car(Honda, 940000), Car(Lamborghini, 5100000), Car(Tesla, 6250000), Car(Nissan, 7700000)]

 

Summary

There are plenty of other built-in functions that Python provides, each has its own area of usage. You can explore many such Python functions from python.org official documentation.

Leave a Comment