Advanced Python Concepts

Advanced Topics In Python

Let’s take a look at some of the more advanced Python concepts today. While we’ve already talked about some of these concepts in earlier tutorials, this page will serve you as a quick guide for the common advanced concepts for your Python learning.

Brief List of the Advanced Python Concepts

Without any further ado, let’s go ahead with our first advanced concept.

1. Lambda Function

In Python, a lambda function is a single-line function that is declared anonymous i.e., declared with no name, which may have a number of arguments, but it has only one expression.

Syntax:

lambda arguments: expression
  • As seen in the syntax below, lambda function is declared by using the keyword “lambda”.
  • Then we write a list of arguments, lambda function can take any number of arguments, but it cannot be zero. After the colon, we write an expression that applies these arguments to any practical operation. Syntactically, lambda function is restricted to a single expression only, i.e. It can contain only one expression and not more than that.

Example :

remainder = lambda number: number%2
print (remainder (25))

Explaination:

In the above code, lambda num: number%2 is the lambda function. The number is the argument while number % 2 is the expression that is evaluated and the result is returned.

The expression derives the input modulus of input 2. We give 25 as a parameter, divided by 2, we get the remaining 1.

You should note that the lambda function in the script above is not given any name. It simply returns the given item to the rest of the identifier.

However, even though it was not known, it was possible for us to call it the same as we call normal function.

Here’s another example of lambda function:

addition = lambda a, b: a+b
print (addition (19,55))

Output: 74


2. Comprehensions in Python

Comprehension in Python deliver us with a compressed but crisp way to contrive new sequences (such as lists, set, dictionary etc.)

Python supports 4 types of comprehension

  • List comprehension
  • Dictionary comprehension
  • Set
  • Generator

List Comprehension

A list is one of the basic data types in Python. Whenever you encounter a variable name followed by a square bracket [ ], or list builder, it is a list that can contain multiple items, making it a type of data that is integrated. Similarly, it is also a good idea to announce a new list and then add one or more items to it.

Example:

even_numbers = [2, 4, 6, 8, 10]
print (even_numbers)

Output:

[2,4,6,8,10]

What is list comprehension?

In simple terms, list comprehension is the process of building a new list from an existing list. Or, you can say it is Python’s unique way of adding a for loop to the list. List comprehension, in fact, offers many advantages over traditional lists.

Firstly, the code does not exceed one line, making it easy to declare and read. It is also convenient to comprehend the lists using comprehension than using for loop. Lastly, it is also a simple, quick, and accurate way to create a new, more dynamic list.

Syntax:

[expression for item in list]

OR

[expression for item in list if conditional]

Syntax of list comprehension is a bit different from the other syntax as the expression is mentioned before the loop, but that’s how it is done.

Example:

n_letter = [letter for letter in 'encyclopedia']
print(n_letter)

Output:

[‘e’, ‘n’, ‘c’, ‘y’, ‘c’, ‘l’, ‘o’, ‘p’, ‘e’, ‘d’, ‘i’, ‘a’]


Dictionary Comprehension

Dictionaries are Python implementations of a data structure known as the associative array. The dictionary contains a set of key values. Each pair of keys sets the key to their corresponding value. You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value:

Example:

thisdict = {"name": "Ford","age": 34, "last_name": "Mustang"}
print(thisdict)

Output:

{'name': 'Ford', 'age': 34, 'last_name': 'Mustang'}

What is Dictionary comprehension?

Dictionary comprehension is similar to list comprehension with additional requirements of defining a key:

Syntax:

output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}

Example:

In this example, we’ll perform the same function as we’d do with the comprehensions by using a regular function.

sq_dict = dict()
for number in range(1, 9):
    sq_dict[number] = number*number
print(sq_dict)

Now, let’s try the same function using dictionary comprehension

square_dict = {num: num*num for num in range(1, 9)}
print(square_dict)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

Set Comprehension

Sets are used to store multiple items in a single variable. A set is one of 4 types of data built into Python used to store data collections. The other 3 List, Tuple, and Dictionary, all with different attributes and uses.

Example:

brand_set = {"Mustang", "Ferrari", "Ford","Aston Martin"}
print(brand_set)

Output:

{'Aston Martin', 'Mustang', 'Ford', 'Ferrari'}

What is set comprehension?

Set Comprehension is similar to list comprehension. The only difference between them is that the set comprehensions use curly brackets {}. Let’s look at the following example to understand the set understanding.

Syntax:

{expr for variable in iterable}

OR

{expression for variable in iterable if condition}

Example:

s = [1,2,3,4,5,4,6,6,7,8,8,]
using_comp = {var for var in s if var % 2 ==0}
print(using_comp)

Output:

{8, 2, 4, 6}

Generator Comprehension

A generator is a special type of iterator, which maintains instructions on how to produce its individual components, respectively, and its current state of replication. It produces each member, one at a time, only as requested by iteration.

Syntax:

(expression for var in iterable if condition)

What is generator comprehension?

Generator comprehension is very similar to list comprehension. One difference between them is that generator comprehension uses round brackets and list comprehension uses square brackets.

The main difference between them is that the generators do not set the memory for the entire list. Instead, they produce each value individually which is why they work so well in memory.

Example:

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] 
output_gen = (var for var in input_list if var % 2 == 0) 
print("Output values using generator comprehensions:", end = ' ') 
for var in output_gen: 
     print(var, end = ' ')

Output:

Output values using generator comprehensions: 2 4 4 6

3. Decorator Functions

Decorators are powerful and resourceful tools that allow programmers to transform the performance of functions without affecting their basic functionality.

You can think of other activities like plain donuts; decoration process for applying coatings to donuts. No matter how you decorate them, they are still donuts.

In other words, decorators allow the programmers to wrap another function in order to increase the performance of the wrapped function without changing their internal algorithm.

Syntax:

@dec2
@dec1
def func (arg1, arg2, ...):
    pass

4. Hashability

Hashability is a feature of Python objects that tells whether an object has a hash value or not. If an item has a hash value it can be used as a dictionary key or as a pre-set item.

An object is hashable if it has a fixed hash value throughout its life. Python has a built-in hash method (__hash __ ()) that can be compared to other objects.

Comparing requires the __eq __ () or __cmp __ () method and if the hashable items are equal they have the same hash value.

Example:

s1 = (2,4,6,8,10)
s2 = (1,3,5,7,9)
#shows the id of the object
print(id(s1))
print(id(s2))

Output:

1898434378944
1898436290656

In the example above, two items are different as non-convertible types of hash value depend on the data stored and not on their id.

The great advantage of using hashes is the quick search time (e.g., O (1) complex time) for fetching an item from a dictionary. Similarly, checking that something is a set takes a normal amount of time.

In other words, using hashing as a start-up process provides high performance for a variety of standard operations, such as object detection, object installation, and object testing, using a head above having a hash table under the hood.


Conclusion

In this article, we have reviewed five high-level concepts in Python. Here is a quick review of the most important information to take.

  • Lambda activities: You use lambda functions to perform a simple task, usually within another function call, such as filter () or max ().
  • Comprehension: They are a simple and effective way to make lists, dictionaries, and collections from the system.
  • Generators: Lazily- evaluated iterator that offers items only when requested, and as a result, they work very well in memory. They should be used when working with big data in sequence.
  • Decorators: Decorators are useful when you want to find other non-algorithmic changes and current functions. In addition, decorators can be used repeatedly. Once defined, they can decorate as many functions as you want.
  • Hashability: Strength is a necessary component of Python objects that can be used as dictionary keys or set objects. They offer a way to bring back and install something effective, as well as membership testing.

This was in brief about some advanced topics in python.

Hope this helps!