paint-brush
The Pythonic Way Of Doing Things (includes Code)by@devonroll
1,808 reads
1,808 reads

The Pythonic Way Of Doing Things (includes Code)

by KaranSeptember 22nd, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The most common data types in python are float (floating point), int (integer), str (string), bool (Boolean), list, and dict (dictionary) Unlike C or C++, Python will automatically determine which data type it will store data as. We can create our own data structures in python apart from the data structures provided by python. All you have to do is create a class and define your own methods in that class. Python generators are a simple way of creating iterators / iterable objects. Decorators are just a fancy name and way of passing a function as an argument to another function.
featured image - The Pythonic Way Of Doing Things (includes Code)
Karan HackerNoon profile picture

Disclaimer: This blog is not about the zen of python. This blog is about solving problems in python in a simple and easy way. This blog is also about the tricks and code paradigms that you might see in other people code.Lets get started !!

Introduction

As a coder (in my head), I always like to start things by describing data types. I think they are an excellent way to learn and explain any new concepts of language. So what are data types in python ?? Lets take a look-

A data type or simply type is an attribute of data which tells the interpreter how the programmer intends to use the data. As we all know, The most common data types in python are float (floating point), int (integer), str (string), bool (Boolean), list, and dict (dictionary). But unlike C or C++, Python will automatically determine which data type it will store data as. but you need to be aware of data types in order to convert data from one type to another(also called as Typecasting or Type conversion). Lets look at an example of basic data type (List) to understand the language and programming as a whole .

## I am simply creating a list and printing out the type of indivisual elements in the list .. 
List = [1,2.0,"Hello World",True,[1,2,3,4,5],{'key':'value'}]

# I am using for in loop because the size of the list is fixed ..
for element in List:
    print(type(element))

# or you can also use list compreshension     
elements = [type(element) for element in List]
print(elements)

# output //
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'dict'>
[<class 'int'>, <class 'float'>, <class 'str'>, <class 'bool'>, <class 'list'>, <class 'dict'>]

Remember — We can create our own data structures in python apart from the data structures provided by python. All you have to do is create a class and define your own methods in that class. That’s how a dataframe of pandas is created … But i will write about it some other day. For now lets stick to some basics !!

Basic List Methods

Lets look at some List Methods to insert and remove an element from the list …

1. append : to add an element in a list. Performance : Time Complexity for appending an element at the back of the list is o(1) while anywhere else is o(n)

2. remove : to remove an element in a list. Performance : Time complexity for removing an element in the list is o(n)

Time Complexity for Searching an element in List is always o(1)

## List Methods ...

# insertion 
List.append((1,5.0))
print(List)

# seraching an element in the list which is already in a list ... 
list_in_list = List[4][0] 
print(list_in_list)

# deletion 
List.remove(1)
print(List)

# output //
[1, 2.0, 'Hello World', True, [1, 2, 3, 4, 5], {'key': 'value'}, (1, 5.0)]
1
[2.0, 'Hello World', True, [1, 2, 3, 4, 5], {'key': 'value'}, (1, 5.0)]

Manipulating List Items

1. lambda Function : they are written in 1 line and used to define custom functions

2. map() Method (also called as a vector method in DataScience): use map function to map a custom function defined by you to every element of a list. map method takes 2 arguments —

a. function you want to apply
b. list you want the above function to apply

3. enumerate() Method : The enumerate() method adds counter to an iterable and returns it. The returned object is a enumerate object.

custom_list = [[1,2,3,4,5],["Cat","Dog","Dog","Tiger","Lion","Goat"]]

# custom function to find square of a number 
def square_of_number(x):
    return x*x 

# using lambda functions to create a new list from exisitng list but with cube of each items in the list..
cube_of_number = lambda x:x*x*x
squares_of_list_items = lambda x:x*x
# using map function to apply a function to all elements of the list  
new_list_of_squares = list(map(squares_of_list_items,custom_list[0]))
new_list_of_cubes = list(map(cube_of_number,custom_list[0]))

print(new_list_of_squares)
print(new_list_of_cubes)

# Using Enumerate to find the count of Each animal in custum_list 
for i,x in enumerate(custom_list[1]):
    print('iterater is :', i ,'and value is ', x)

# output //
[1, 4, 9, 16, 25]
[1, 8, 27, 64, 125]
<enumerate object at 0x7f0cf44e4b40>
iterater is : 0 and value is Cat
iterater is : 1 and value is Dog
iterater is : 2 and value is Dog
iterater is : 3 and value is Tiger
iterater is : 4 and value is Lion
iterater is : 5 and value is Goat

Generators and Decorators :

1. Python generators are a simple way of creating iterators / iterable objects . It is something which can be paused at the function call time and can be resumed anytime during the life cycle of the entire program by using next() function .

2. Decorators are first class objects in python . It means that they can be passed by reference in any function . Decorator is just a fancy name and way of passing function as an argument to another function. they are also called as callable objects that takes in a function and returns or change the behaviour of that function .

# Generators : 
def generator():
    for i in range(5):
        yield i
print(generator)   # output:// <function generator at 0x7fd59831ad08>
a = generator()
print(next(a))     # output:// 0
print(next(a))     # output:// 1 

# Decorators 
def function1():
    print('this is function 1')
    
def function2(function_argument):
    function_argument()
    print('this is function 2')
    
new_object = function2(function1)  # output:// this is function 1 this is function 2

# using it as a decorator function ... 
@function2
def function1():
    print('this is function 1')    # output:// this is function 1 this is function 2

*args and **kwargs

args and **kwargs are the most important keywords which i personally use a lot in my coding style and programming practice. well, imagine this !! you are creating a function and you don’t know the expected number of parameters . we use *args in that case and if its a dictionary , then use **kwargs .


def arr(*args):
    for i in args:
        print(i)

arr(1,2,3,4) # output: // 1 2 3 4 
arr(1,2)     # output:// 1 2 

Python is a great programming language. It is easy to learn and quick to implement. It supports a lot of packages therefore it is used by many hackers , data scientists and back-end developers to perform their everyday tasks.

That's it for this post . Hope you liked it .