25 Python Examples
Tags: python, beginners
Published: 2020-03-12 16:16:11

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 <a href="https://gumroad.com/l/dcsp">this book</a>

## Examples

Swap values between two variables

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

Check if the given number is even

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

Split a multiline string into a list of lines

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

Find memory used by an object

```python
import sys
print(sys.getsizeof(6))
```

Reverse a string

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

Print a string n times

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

Check if a string is a palindrome

```python
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

```python
print(','.join(strings))
```

Find the first element of a list

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

Find elements that exist in either of the two lists

```python
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

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

Find the average of a list of numbers

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

Check if a list contains all unique values

```python
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

```python
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

```python
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

```python
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

```python
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

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

Find unique characters in a string

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

Use lambda functions

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

Use map functions

```python
def multiply(n): 
    return n * n 
  
list = (1, 3, 5) 
result = map(multiply, list) 
print(list(result))
```

Use filter functions

```python
arr = [1, 2, 3, 4, 5]
arr = list(filter(lambda x : x%2 == 0, arr))
print (arr)
```

```python
import pandas as pd
import numpy as ns
```

Use list comprehensions

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

Use slicing operator

```python
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

```python
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:
* <a href="https://python.org">Python official site</a>
* <a href="https://pythonbasics.org">Learn Python</a>