Ivy Apr 02, 2020 No Comments
We have covered Python Data Types and Loops in Python earlier. I hope you find them useful. Moving ahead with our Python learning, in this article we are going to talk about the top 15 interesting tricks every Python beginner must know.
First of all, let us understand about Functions and Methods.
A Function is an independent block of code that can be called by its name with or without any parameter. We can create a function that does or does not return any value as an output.
All methods are functions associated with an object of the class in which it is defined.
Now we will explain various Functions and Methods related to Strings and Lists along with some examples.
This method can be used to convert the first letter of the words in a string to its upper case. We can get a look at the way we write the title of any article.
a = "corona virus spreads throughout the planet" a.title()
As the name suggests, this method is to convert the uppercase letter to lower case and vice versa.
a = "cORONA vIRUS sPREADS throughout the planet" a.swapcase()
We can use the split method to split a string on a separator. An option to split the string as many times as we want is also available.
a = "My Name Is Donald Trump" a.split()
a = "My-Name-Is-Donald-Trump" a.split(sep="-")
a = "My-Name-Is-Donald-Trump" a.split(sep ='-',maxsplit=3)
If we want to replace a word with another, we can use the replace method on the String object.
a = "My Name Is Donald Trump. I like Mickey Donald and McDonald" a.replace('Donald', 'Obama')
a = "." a.join("UNICEF")
a = "Name " b = "Place"a.join(b)
To find the index of the first match of any character in a string, we can use the index method on the String object. The 2 different commands shown below gives the same output that is the first instance of matching of character “C”.
a = "UNICEF" a.index("C")
a = "UNICEF UNICEF UNICEF"a.index("C")
a = "UNICEF UNICEF UNICEF" a.index("CEF")
To convert the first letter in a string to an upper case, we can use this method.
a = "unicef unicef unicef" a.capitalize()
A very interesting method provided in Python is to reverse iterable elements.
a = ["Name", "Surname", "Age", "City"] a.reverse() print(a)
lambda helps code simple anonymous functions. It is a single line function which can have any number of the argument. A Lambda function is restricted to contain only a single expression. These are used when you need a function for a short period. Let us look at some examples.
cube = lambda x : x*x*x cube(9)
The above code gives the cube of a number. We did not define a function explicitly which simplifies our task to a great extent.
The below set of code allows us to join the two columns of our data Data Frame.
data = {'Name':["Donald" , "Barack" , "Sachin", "Mary"], 'Surname':["Trump","Obama","Tendulkar","Kom"]} import pandas as pd data = pd.DataFrame(data, index=None) data['Full Name'] = data[['Name', 'Surname']].apply(lambda x: ' '.join(x), axis = 1) print(data)
reverse_string = lambda s: s[::-1] reverse_string('hello my name is Anthony Gonsalves')
It is a function we can apply on a list to count the number of occurrences of its elements. Counter makes our task of counting values very easy.
from collections import Counter list_of_digits = [1,2,3,4,5,5,2,2,2,3,4,5,3,2,1,3,4] count = Counter(list_of_digits)
If we want to apply a function on a sequence of an iterable list, reduce comes in handy used along with a lambda function. The reduce function works in a below-mentioned manner:
To find the maximum number in a list of numeric elements, we use the below provided reduce command.
#Syntax : reduce(function, sequence) from functools import reduce list2 = [3,4,5, 33, -33, 234, 1, 223] reduce(lambda x,y :x if x>y else y , list2)
The filter function creates a new iterator from the existing iterable based on some filter condition wherever it gives true value.
#Syntax: filter(function, sequence) list1 = [1,2,'a',4,5,'b',7,8,9] list(filter(lambda x : type(x)==int , list1))
The range is a simple function that helps create a sequence of numbers. We can give three arguments that are start value, stop value, and step to generate the sequence.
#Syntax: range(start, stop, step) for item in range(1,10): print(item)
The map function applies a function on each element of a sequence and returns a map iterable object containing the results.
#Syntax: map(function, iterable) First_List = [3,6,2,1,9] list(map(lambda x : x*x, First_List ))
As the name suggests, we can apply this method to generate a sorted sequence of an iterable. The ‘reverse’ argument is set to True or False to get a descending or an ascending sorted output.
First_List = [3,6,2,1,9] (First_List.sort(reverse=True)) print(First_List) First_List = ['z','x','t','w'] (First_List.sort(reverse=True)) print(First_List)
The enumerate built-in function is very useful when we want to loop over something and have a counter. We can also pass an optional argument ‘start’ which helps us start the index of the counter from wherever we want. By default, the start parameter value is 0. The returned object is an enumerate object.
#Syntax : enumerate(iterable, start) Names = ["Chris","Kalam","Sandeep"] Names.sort() for Roll_no,j in enumerate(Names ,1): print('{}:{}'.format(Roll_no,j)) The code above takes a list of names, sorts it, and then uses an enumerate function to generate a counter named as roll_no in this case.
A very interesting short cut Python provides is for interchanging values of 2 variables. Usually, it requires another temporary variable to complete the swapping task. Python makes it very easy to swap values with the below set of commands in the image.
Leave a Reply