25 Python Examples

days_64

Python64

Posted on March 12, 2020

25 Python Examples

This is a list of 25 examples for the Python programming language. They are common examples that you may use while programming.

The examples are code only and should be self-explicatory. If you are new to Python, you may like this book

Examples

Swap values between two variables

a = 4
b=6
a,b=b,a
print(a)
print(b)

Check if the given number is even

def is_even(num):
    return num % 2 == 0
is_even(12)

Split a multiline string into a list of lines

def split_lines(s):
    return s.split('\n')
split_lines('This is\n python\n data')

Find memory used by an object

import sys
print(sys.getsizeof(6))

Reverse a string

language = "python"
reversed_language = language[::-1]                                                              
print(reversed_language)

Print a string n times

def repeat(string, n):
    return (string * n)
repeat('python',5)

Check if a string is a palindrome

def palindrome(string):
    return string == string[::-1]
palindrome('python')
#palindrome mean a words or phrase or sequence that reads the same backwards as forwards

Combine a list of strings into a single string

print(','.join(strings))

Find the first element of a list

def head(list):
    return list[0]
print(head([1, 2, 3, 4, 5]))

Find elements that exist in either of the two lists

def union(a,b):
    return list(set(a + b))
union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4])

Find all the unique elements present in a given list

def unique_elements(numbers):
    return list(set(numbers))
unique_elements([1, 2, 3, 2, 4])

Find the average of a list of numbers

def average(*args):
    return sum(args, 0.0) / len(args)
average(5, 8, 2)

Check if a list contains all unique values

def unique(list):
    if len(list)==len(set(list)):
        print("All elements are unique")
    else:
        print("List has duplicates")
unique([1,2,3,4,5])

Track frequency of elements in a list

from collections import Counter
list = [1, 2, 3, 2, 4, 3, 2, 3]
count = Counter(list)
print(count)

Find the most frequent element in a list

def most_frequent(list):
    return max(set(list), key = list.count)
numbers = [1, 2, 3, 2, 4, 3, 1, 3]
most_frequent(numbers)

Convert an angle from degrees to radians

import math
def degrees_to_radians(deg):
    return (deg * math.pi) / 180.0
degrees_to_radians(90)

Calculate time taken to execute a piece of code

import time
start_time = time.time()
a,b = 5,10
c = a+b
end_time = time.time()
time_taken = (end_time- start_time)*(10**6)
print("Time taken in micro_seconds:", time_taken)

Find gcd of a list of numbers

from functools import reduce
import math
def gcd(numbers):
    return reduce(math.gcd, numbers)
gcd([24,108,90])

Find unique characters in a string

string = "thisisapythonstring"   
unique = set(string)
new_string = ''.join(unique)
print(new_string)

Use lambda functions

x = lambda a, b, c : a + b + c
print(x(5, 10, 20))

Use map functions

def multiply(n): 
    return n * n 

list = (1, 3, 5) 
result = map(multiply, list) 
print(list(result))

Use filter functions

arr = [1, 2, 3, 4, 5]
arr = list(filter(lambda x : x%2 == 0, arr))
print (arr)
import pandas as pd
import numpy as ns

Use list comprehensions

numbers = [1, 2, 3]
squares = [number**2 for number in numbers]
print(squares)
[1, 4, 9]

Use slicing operator

def rotate(arr, d):
    return arr[d:] + arr[:d]

if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5]
    arr = rotate(arr, 2)
    print (arr)
[3, 4, 5, 1, 2]

Use chained function call

def add(a, b):
    return a + b
def subtract(a, b):   
    return a - b
a, b = 5, 10
print((subtract if a > b else add)(a, b))

More Python:

💖 💪 🙅 🚩
days_64
Python64

Posted on March 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024