5 things every Python programmer should know

5 things every Python programmer should know

In this article, we cover 5 essential skills every Python programmer should know

1. List Comprehensions:

List comprehensions is a feature in Python which allows for creation of lists in a compact way. In order to create lists using list comprehensions, other Iterables such as strings, tuples, range(N) or other lists are used. Syntax of List comprehensions ::

new_list = [ expression for element in iterable ]        

In the above syntax, expression determines the final value of the list element for every element of the iterable.

Let’s look at an example of creating a list of squares of first 10 natural numbers ::

n_numbers = [ x * x for x in range(1, 11) ]        

  • here expression is: x * x
  • iterable is :: range(1, 11)
  • Iterating over the iterable gives us elements from 1–10

Some other examples of list comprehensions ::

Declaring a 3 x 3 matrix of 0s using List comprehensions :: rows = 3 cols = 3 matrix = [ [0] * rows for i in range(cols) ]        

2. Lambda Expressions:

Lambda functions are anonymous inline functions which are mostly used inside of other functions.

Syntax:

lambda arguments : expression        

Let’s look at an example of a Lambda function which returns square of a number

square = lambda a: a ** 2 square(2)        

Here’s an another example of a lambda to check whether a number is even

check_even = lambda a: True if a & 1 == 0 else False check_even(2)        

3. Loops can have else statement:

In Python, for loop and while loop can have **optional** else statement.

Let’s look at the syntax:


for i in iterable: < operation > else: < operation >        

In case of a?While?loop:

while( condition ): < operation > else: < operation >        

Let’s take an example:

Problem: Given an array of integers, print the index of the even element if the array holds an even number and if not then return -1 ?

Example-1 Without using the else statement

#! /bin/python
has_even = False
idx = None
arr = [ 1, 3, 5, 9, 11 ]
check_even = lambda a: True if a & 1 == 0 else False
for i in range(len(arr)):
    if check_even(arr[i]):
     has_even = True
  idx = i
  break
  
if has_even:
    print(idx) 
else:
    print(-1)        

Example-2 Using the else statement

#! /bin/python
arr = [ 1, 3, 5, 9, 11 ]
check_even = lambda a: True if a & 1 == 0 else False 
for i in range(len(arr)):
    if check_even(arr[i]):
     print(i)
  break
else:
    print(-1)        

As we can notice in the above example, there’s no need to maintain flag when using the else based syntax. We can construct similar example when using while loop as well.

4. Python Collections :: Counter

Python has a builtin Collections module which provides several specialized container datatypes. Counter is one of the datatype offered by collections module. It’s basically a subclass of dict for counting hashable objects. A common use case could be calculate the number of characters in a given string e.g. ::

c = Counter("thiiss wiill caalcullateeee theee numbeeer of characters")        

if we print c, it will now have the following data:

Counter({'e': 11, ' ': 6, 'l': 5, 'a': 5, 't': 4, 'i': 4, 'c': 4, 'h': 3, 's': 3, 'r': 3, 'u': 2, 'w': 1, 'n': 1, 'm': 1, 'b': 1, 'o': 1, 'f': 1})        

And now we can check the occurrence of each of the characters as follows:

count_e = c.get('e') # returns 11        

5. Current dir and parents:

We can use Python’s builtin module pathlib to get current and parent directories from the script’s pat


from pathlib import Path
# get the current path
current_path = Path(__file__).resolve() 
 # /Users/john/pycodes/script.py
 
parent_directory = current_path.parent 
# /Users/john/pycodes
grand_parent = current_path.parent.parent 
# /Users/john 
# In this way we can go up to all the levels        

Summary:

In this article, we learned about 5 things which every Python programmer should know irrespective of whether they work as a developer, data scientist, data engineer, automation engineer or at any other role. This 5 things will definitely give you an edge when writing Python code.

Originally published at?https://pyrootml.com.


要查看或添加评论,请登录

社区洞察

其他会员也浏览了