100 Python Examples

Python coding examples

In this article, you will find a comprehensive list of Python code examples that cover most of the basics.

This list of 100 useful Python examples is intended to support someone who is:

  • Preparing for a coding interview.
  • Preparing for an examination.
  • Exploring what programming is.
  • Teaching Python and wants to find useful examples

Without further ado, let’s get coding!

Table of Contents

1. Print ‘Hello World!’ in Console

The simplest and probably the most common example of Python is the “Hello world” program.

Here is how it looks:

print("Hello World!")

Output:

Hello World!

2. Ask User Their Name and Greet Them

To ask for user input in Python, use the input() function.

For instance, you can store user input to a variable and use that variable in a greeting.

Here is the code:

name = input("Please, enter your name: ")

print(f"Hello, {name}!")

Output:

Please, enter your name: Jack
Hello, Jack!

3. Create a List of Names in Python

To create a list in Python, add comma-separated values between braces.

For instance, here is a list of names in Python:

names = ["Alice", "Bob", "Charlie"]

4. Merge Two Lists

Given two or more lists in Python, you may want to merge them into a single list.

This is easy in Python. Use the + operator you would use when summing up numbers. In the case of lists, this merges the lists into one.

For instance:

numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]

merged = numbers1 + numbers2

print(merged)

Output:

[1, 2, 3, 4, 5, 6]

5. Loop Through a List of Names and Print Each

A powerful feature of Python lists is that they are iterable.

In other words, you can easily loop through the items on the list to do something for them.

For example, let’s create a list of names and print each name into the console:

names = ["Alice", "Bob", "Charlie"]

for name in names:
    print(name)

Output:

Alice
Bob
Charlie

6. Get Rid of Spaces in Python String

To get rid of spaces in a Python string, replace all blank spaces with an empty string.

You can do this with the replace() method.

For instance:

sentence = "Hello, this is a sentence."

no_spaces = sentence.replace(" ", "")

print(no_spaces)

Output:

Hello,thisisasentence.

7. Calculate the Number of Spaces in a String

A Python string has a built-in method count(). You can use it to count how many times a substring occurs in a string.

For instance, let’s calculate how many blank spaces there are in a string:

sentence = "Hello, this is a sentence."

num_spaces = sentence.count(" ")

print(f"There are {num_spaces} spaces in the sentence.")

Output:

There are 4 spaces in the sentence.

8. Check If a String Is a Palindrome

To check if a string is a palindrome in Python, that is, same when reversed:

  • reverse the string and compare it with the original string.

For example:

def is_palindrome(word):
    if word == word[::-1]:
        print(f"The word {word} is a palindrome.")
    else:
        print(f"The word {word} is not a palindrome.")

is_palindrome("redivider")

Output:

The word redivider is a palindrome.

9. Find a Substring in a String

To find a specific substring inside a string in Python, use the built-in find() method of a string.

For example:

sentence = "This is just a test"
target = "just"

idx = sentence.find(target)

print(f"The word '{target}'' starts at index {idx} in '{sentence}'")

Output:

The word 'just' starts at index 8 in 'This is just a test'

10. Add Two Numbers

To create a function that adds two numbers:

  • Create a function that takes two number arguments
  • Sum up the arguments
  • Return the result

For example:

def sum(a, b):
    return a + b

print(sum(1,2))

Output:

3

11. Find Maximum of Two Numbers in Python

To find the maximum value between two (or more) numbers in Python, use the built-in max() function.

For instance:

n1 = 10
n2 = 100

maximum = max(n1, n2)

print(f"The maximum number is {maximum}")

Output:

The maximum number is 100

12. Find the Minimum of Two Numbers in Python

To find the minimum value between two (or more) numbers in Python, use the built-in min() function.

For instance:

n1 = 10
n2 = 100

minimum = min(n1, n2)

print(f"The minimum number is {minimum}")

Output:

The minimum number is 10

13. Find the Average of a List of Numbers in Python

To compute the average of something, you need to know two things:

  1. The number of elements.
  2. The sum of all the elements.

Given these, you can calculate the average by sum/length.

In Python, you can do it like this:

nums = [1, 2, 3, 4, 5]

total = sum(nums)
length = len(nums)

average = total / length

print(f"The average of {nums} is {average}")

Output:

The average of [1, 2, 3, 4, 5] is 3.0

14. Check If a Year Is a Leap Year in Python

By definition, a leap year is a year that:

  • Is divisible by 4…
  • And not divisible by 100…
  • Unless also divisible by 400.

In Python, you can write a function that implements these three checks to find if a given year is a leap year.

Here is how:

# A function that checks if a year is a leap year
def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

# Example
year = 2020

if is_leap(year):
    print(f"The year {year} is a leap year")
else:
    print(f"The year {year} is not a leap year")

Output:

The year 2020 is a leap year

15. Find The Maximum Value of a Python Dictionary

To find the maximum value of a dictionary, you need:

  1. To access all the values of the dictionary using the dict.values() method.
  2. Find the greatest value using max() function.
data = {"Alice": 23, "Bob": 54, "Charlie": 12}

ages = data.values()

max_age = max(ages)

print(f"The oldest person is {max_age} years old.")

Output:

The oldest person is 54 years old.

16. Merge Two Python Dictionaries

To merge two dictionaries in Python, use the double-asterisk notation to unpack the dictionary items into one dictionary.

For example, here is a function that does it for you:

# Merger function
def merge(d1, d2):
    return {**d1, **d2}
    
# Example code
data1 = {"Alice": 23, "Bob": 32}
data2 = {"Charlie": 77, "David": 19}

both = merge(data1, data2)

print(both)

Output:

{'Alice': 23, 'Bob': 32, 'Charlie': 77, 'David': 19}

17. Check If a Key Exists in a Python Dictionary

To check if a key exists in a dictionary, you can use the in operator.

For instance:

data1 = {"Alice": 23, "Bob": 32}

exists = "Alice" in data1

print(exists)

Output:

True

18. Delete an Element from a Python Dictionary

To delete an entry from a dictionary, use the del operator.

For example:

data1 = {"Alice": 23, "Bob": 32}

del data1["Alice"]

print(data1)

Output:

{'Bob': 32}

Learn more about dictionaries in Python.

19. Find the Distance Between Two 2D Points in Python

To calculate the distance between two points, use the Pythagorean theorem.

For example, here is a function that calculates the distance between two 2D points.

from math import sqrt

def distance(p1, p2):
    return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
    
start = (1, 1)
end = (2, 2)

dist = distance(start, end)

print(f"The distance between {start} and {end} is {dist}")

Output:

The distance between (1, 1) and (2, 2) is 1.4142135623730951

Notice that there is a built-in function dist() in the math module that does the exact same for you:

from math import sqrt, dist

start = (1, 1)
end = (2, 2)

dist = dist(start, end)

print(f"The distance between {start} and {end} is {dist}")

Output:

The distance between (1, 1) and (2, 2) is 1.4142135623730951

20. Read a File Line by Line in Python

To open a file, and read it line by line in Python, you need to:

  1. Open a file behind a path.
  2. Read and store the lines of the file.
  3. Close the file.

To do this, use a context manager. A context manager automatically closes the file once processing has been completed.

To open the file with a context manager, use the with statement.

Given a file example.txt in the same folder that looks like this:

This is a test
The file contains a bunch of words
Bye!

You can read the file line by line with a context manager using the following code:

with open("example.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line)

Output:

This is a test

The file contains a bunch of words

Bye!

21. Check If a File Contains a Specific Word

To check if a file has a specific word, you need to:

  1. Open the file behind the path.
  2. Read the contents of the file in memory.
  3. Test if a specific word is found in the content.
  4. Close the file.

To do this, use a context manager. A context manager automatically closes the file once processing has been completed.

To open the file with a context manager, use the with statement.

Given a file called example.txt with contents like this:

This is a test
The file contains a bunch of words
Bye!

You can check if a specific word exists in that file with this piece of code:

with open("example.txt", "r") as file:
    has_word = "test" in file.read()
    if has_word:
        print("The file has the word 'test'")

Output:

The file has the word 'test'

22. Count the Frequency of a Word in a File

To count the frequency of a specific word in a text file in Python:

  1. Open the file behind the path.
  2. Read the contents of the file in memory.
  3. Count the number of occurrences of a string.
  4. Close the file.

To do this, use a context manager. A context manager automatically closes the file once processing has been completed.

To open the file with a context manager, use the with statement.

Given a file called example.txt with contents like this:

This is a test
The file contains a bunch of test words
Bye!

You can check many times the word “test” occurs in a file by:

with open("example.txt", "r") as file:
    n = file.read().count("test")
    print(n)

Output:

2

23. Swap Two Values without a Third

This is one is a classic examination question.

Is there a way to swap two variables without a third helper variable?

The answer is yes. You can use tuple unpacking to achieve this.

For example:

a = 1
b = 2

a, b = b, a

print(a, b)

Output:

2 1

24. Check If a Given Number Is a Prime Number

A prime number is any positive non-zero number that is only divisible by itself or by 1.

For example, 11 is a prime number.

To create a Python program that finds if a number is a prime number, you need to:

  1. Have a target number.
  2. Ensure the number is more than 1.
  3. Loop through all the numbers that are less than half the target number.
  4. Check if any number divides the target evenly.

For example, to check if 11 is a prime number, you need to check if any of the following numbers divides it evenly: 2, 3, 4, 5.

Here is a Python program that checks if a given number is a prime number:

def is_prime(number):
    if number > 1:
        for i in range(2, int(number / 2) + 1):
            if number % i == 0:
                print(f"{number} is not a prime number.")
                break
        else:
            print(f"{number} is a prime number.")
    else:
        print(f"{number} is not a prime number.")
        
is_prime(11)
is_prime(7)
is_prime(16)

Output:

11 is a prime number.
7 is a prime number.
16 is not a prime number.

25. Calculate Simple Interest in Python

Simple Interest is calculated using the following formula:

SI = (P × R × T) / 100

Where:

  • P = Principal amount of money.
  • R = Rate of Interest (e.g. 7%).
  • T = Time period.

The principal is the sum of money that remains constant for every year in the case of simple interest.

Here is a Python program to figure out the simple interest:

def simple_interest(p, t, r):
    """
    p = principal amount
    t = time interval
    r = rate of interest
    
    si = simple interest given p, t, r
    """
      
    si = (p * t * r)/100
      
    print("The Simple Interest is", si)
    return si
    
simple_interest(1200, 10, 7)

Output:

The Simple Interest is 840.0

This returns the earnings during the period. To get the total amount of money, add this result to the principal amount.

26. Ask a Word from User and Reverse It

In Python, you can reverse a string by calling string[::-1].

For example, to ask the user a word and reverse it, use the following piece of code:

word = input("Give a word, I will reverse it: ")

print(word[::-1])

Example run:

Give a word, I will reverse it: testing
gnitset

27. Ask User a Sequence of Numbers and Reverse Them

To create a program that asks the user for a sequence of numbers and reverses it:

  1. Ask user for comma-separated number input.
  2. Split the resulting string by commas. This creates a list of strings that represent numbers.
  3. Convert the list of number strings to a list of integers.
  4. Call the built-in reversed() function on the list of integers to reverse the order.

Here is the code for you:

# 1
num_strs = input("Give a comma-separated numbers: ")

# 2
num_str_list = num_strs.split(",")

# 3
num_ints = [int(num_str) for num_str in num_str_list]

# 4
reversed_nums = list(reversed(num_ints))

print(reversed_nums)

Output:

Give a comma-separated numbers: 1,2,3
[3, 2, 1]

28. Calculate BMI Index in Python

BMI or Body Measurement Index measures leanness or corpulence given height and weight.

The formula for BMI index given height in centimeters and weight in kilos is:

BMI = weight / (height/100)²

Here is a Python program that asks the user for weight and height and outputs their BMI:

weight = float(input("Enter your weight in kilos: "))
height = float(input("Enter your height in centimeters: "))

BMI = weight / (height/100)**2

print(f"Your weigh {weight}kg and you are {height}cm tall. This gives you BMI index of {BMI}")

Example input:

Enter your weight in kilos: 92
Enter your height in centimeters: 191
Your weigh 92.0kg and you are 191.0cm tall. This gives you BMI index of 25.218606946081522

29. Emit a Beep Sound in Python

On Windows, you can use the winsound module of Python to make a beeping sound.

For example, here is a program that produces a single high-pitch beep that lasts one second:

import winsound

frequency = 2500  # High pitch 2500HZ beep
duration = 1000  # Duration of the beep is 1s

winsound.Beep(frequency, duration)

30. Copy One File to Another in Python

Given a file called example.txt in your project’s folder, you can copy-paste its contents to another.txt file using shutil module’s copyfile function.

from shutil import copyfile

copyfile("example.txt", "another_example.txt")

31. Compute the Factorial of an Integer in Python

In mathematics, factorial is marked with an exclamation mark. Factorial means to multiply the number by all numbers from 1 to the number.

The factorial tells you how many ways there is to arrange n elements.

For example, to figure out how many ways there are to arrange 5 persons in a line, calculate the factorial of five: 5! = 5*4*3*2*1 = 120.

Here is a Python program that calculates the factorial given a number input. It starts with the target number. Then it subtracts one from the target and multiplies the target by this number. It does this until number 1 is reached.

def factorial(number):
    result = 1
    while number >= 1:
        result *= number
        number -= 1
    return result
    
print(factorial(5))

Output:

120

32. Find the Longest Word in a List

Python has a built-in function max(). If you call this function on a list of values, by default it returns the greatest element.

  • In the case of numbers, it returns the largest number.
  • In the case of strings, it returns the string with the highest ASCII value. Not the one with the greatest length!

To make the max() function return the longest string, you need to specify the max() function a second argument, key=len. This shows the max() function that we are interested in the maximum length, not the maximum ASCII value.

For instance:

names = ["Alice", "Bob", "Charlie"]

longest = max(names, key=len)

print(f"The longest name is {longest}")

Output:

The longest name is Charlie

33. Create Pyramid from Asterisks ‘*’

An asterisk pyramid may not be the most useful example, but it surely tests your understanding of loops and maths in Python.

To create a pyramid, you need to start with 1 asterisk. On the next line you have 3, then 5,7, and so on. In other words, the number of asterisks is 2*i + 1, where i is the row number (or the height) of the pyramid.

Now you got the number of asterisks.

Then you need to know how many spaces you need to the left of the asterisks to make it look like a pyramid.

In the first row, the number of spaces is the same as the height of the pyramid. Then on the second row, it is one less. On the third one less again. So you need to add one less space for each row of asterisks. In other words, the number of spaces is h-i-1, where h is the pyramid height and i is the row number.

def pyramid(rows):
    for i in range(rows):
        print(" "*(rows-i-1) + "*"*(2*i+1))

pyramid(12)

Output:

           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
***********************

See also how to create a diamond pattern with asterisks.

34. Find the Intersection of Two Lists in Python

An intersection between two groups refers to the common elements among the groups.

To find the intersection between two lists:

  1. Loop through the other of the lists.
  2. Store the elements that are in the other list as well.
  3. Return the stored elements.

You can use a for loop, but let’s use a more compact expression called list comprehension. This is a shorthand of the for loop:

# A function that finds the intersection between two lists
def intersection(l1, l2):
    return [element for element in l1 if element in l2]

# Example run
names1 = ["Alice", "Bob", "Charlie"]
names2 = ["Alice", "Bob", "David", "Emmanuel"]

names_in_common = intersection(names1, names2)

print(f"Common names among the lists are {names_in_common}")

Output:

Common names among the lists are ['Alice', 'Bob']

35. Convert Celcius to Fahrenheit with Python

To convert temperatures from Celcius to Fahrenheit, use the following formula:

F = (9/5) * celcius + 32

To create a Python program to do this, write a function that:

  1. Takes a temperature in celcius.
  2. Returns temperature in Fahrenheit with the help of the above formula.

Here is the code:

def as_fahrenheit(celcius):
    return 9/5 * celcius + 32
    
c = 37
f = as_fahrenheit(c)

print(f"{c} is {f} in Fahrenheits")

Output:

37 is 98.60000000000001 in Fahrenheits

36. Convert Kilograms to Pounds in Python

To convert weight from kilos to pounds, use the following formula:

p = kilos * 2.2048

To create a Python program to do this, write a function that:

  1. Takes a mass in kilos.
  2. Returns the weight in pounds with the help of the above formula.

Here is the code:

def as_pounds(kilos):
    return 2.2048 * kilos
    
kg = 80
pounds = as_pounds(kg)

print(f"{kg} is {pounds} in pounds")

Output:

80 is 176.38400000000001 in pounds

37. Count the Frequency of Each Letter in a String

To create a character to frequency mapping in Python:

  1. Define a target string.
  2. Create an empty character-to-frequency dictionary.
  3. Loop through the characters of the string.
  4. Add 1 to the frequency dictionary for each character.
  5. Return the dictionary.

Here is how it looks in code:

# A function tha calculates character frequencies in a string.
def letter_frequency(in_string):
    frequencies = {}
      
    for i in in_string:
        if i in frequencies:
            frequencies[i] += 1
        else:
            frequencies[i] = 1
    return frequencies

# Example run    
freqs = letter_frequency("This is just a test string")

print(freqs)

Output:

{'T': 1, 'h': 1, 'i': 3, 's': 5, ' ': 5, 'j': 1, 'u': 1, 't': 4, 'a': 1, 'e': 1, 'r': 1, 'n': 1, 'g': 1}

38. Count the Number of Seconds in a Year

In a year, there are roughly 365.25 days.

In a day there are 24 hours.

In an hour there are 60 minutes.

In a minute there are 60 seconds.

Thus, the number of seconds in a year is:

seconds = 365.25 * 24 * 60 * 60 = 31 557 600

You can calculate this in Python with:

year_seconds = 365.25 * 24 * 60 * 60

print(f"There are {year_seconds} in a year.")

Output:

There are 31557600.0 in a year.

39. Find the Number of Days Between Two Datesin Python

To work with dates in Python, use the datetime module.

To calculate the number of days between two dates (and get leap years correct):

  1. Create two datetime.date objects.
  2. Subtract the more recent date from the more past date.
  3. Call .days() mehod on the resulting date object to get the result.

In Python, it looks like this:

from datetime import date

d1 = date(2021, 3, 22)
d2 = date(2021, 10, 20)

diff = (d2 - d1).days

print(f"The difference between {d1} and {d2} is {diff} days")

Output:

The difference between 2021-03-22 and 2021-10-20 is 212 days

40. Generate Random Numbers Between a Range in Python

In Python, there is a built-in module for generating random numbers called random.

To generate random integers between an interval, call random.randint() method by providing it the max and min values.

For example:

from random import randint

# Print 10 random numbers between 1-100
for _ in range(10):
    print(randint(1,100))

Example output:

97
96
82
70
82
38
47
19
89
99

41. Get a Random Element from a List

The built-in random module comes in with a useful method called choice(). This method randomly selects an element from an iterable.

For example, to pick a random name at a list of strings:

from random import choice

names = ["Alice", "Bob", "Charlie", "David"]

rand_name = choice(names)

print(rand_name)

Output example:

David

42. Check If a Number Is Odd/Even

A number is even if it is evenly divisible by 2. In other words, if there is no remainder after division.

To check if a number is odd, check if it is not divisible by 2.

Here is a Python script that checks if number 3 is odd or even:

number = 3

# Odd = not divisible by 2
# Even = divisible by 2
is_odd = True if number % 2 != 0 else False

print(is_odd)

Output:

True

43. Print a Multiplication Table of an Integer

A multiplication table is a table from where it is easy to check what times what gives what.

To produce a multiplication table of ten, for example, you want to:

  1. Select a target number.
  2. Loop from 1 to 10 and multiply the target number by each number in this range.
  3. Print the result to the console.
# Function that prints multiplication table from 1 to 10.
def mul_table(num):
    for i in range(1, 11):
       print(f"{num} x {i} = {num * i}")
       
# Example call
mul_table(9)

Output:

9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90

44. Print without New Line

By default, printing on a new line adds a new line in Python.

To overcome this, you need to join the printable items together separated by a blank space.

To do this, use the str.join() method on a blank space. This joins the elements of a list separated by a blank space.

Then you can print this whole string. As it is one string, it naturally gets printed on one line.

For example:

names = ["Alice", "Bob", "Charlie", "David"]

print(" ".join(names))

Output:

Alice Bob Charlie David

45. Find a Sum of any Number of Numbers

A Python function can accept any number of arguments. To do this, you need to use an asterisk in front of the argument name. This tells the Python interpreter that there is going to be an arbitrary number of arguments.

For example, let’s create a function that adds up any numbers you pass it:

# A function with * accepts any number of arguments
def sum_nums(*nums):
    # Return the sum of the arguments
    return sum(nums)

# Example usage
s1 = sum_nums(1, 2, 3)
s2 = sum_nums(5, 10, 15, 20, 25, 30)

print(s1, s2)

Output:

6 105

46. Find ASCII Value of a Character in Python

Each character and string in Python has an ASCII value behind the scenes. This value is just an integer ID of that character.

To figure out the ASCII value of a given character, use the built-in ord() function on it.

For instance:

character = "A"

char_ASCII = ord(character)

print(f"The ascii value of '{character}' is {char_ASCII}")

Output:

The ascii value of 'A' is 65

47. Find Factors of a Number

A factor of a number means a number divided by the factor leaves no remainder.

For example, the factors of number 12 are 1, 2, 3, 4, and 6.

To find all factors of a number:

  1. Loop through numbers from 1 all up to the target number.
  2. Check if the number divides the target evenly.
  3. Store each factor into a list.
  4. Finally, return the factors list.

Here is how it looks in Python:

# Loop from 1 to x and check if x is divisible by i
def get_factors(x):
   return [i for i in range(1, x+1) if x % i == 0]

# Example run
number = 460
factors = get_factors(number)

print(factors)

Output:

[1, 2, 4, 5, 10, 20, 23, 46, 92, 115, 230, 460]

48. Simulate Coin Toss in Python

To simulate a coin toss, you need to randomly choose values of 0 or 1.

In Python’s random module, there is a function called choice(). This chooses a value from an iterable randomly.

To simulate coin toss, give this function a list that has 0 and 1. Then based on whether you got 0 or 1, display “Heads” or “Tails” in the console.

Here is how it looks in code:

from random import choice

# A function that randomizes between 0 and 1
def coin_toss():
    states = {1: "Heads", 0: "Tails"}
    one_or_zero = choice([0, 1])
    result = states[one_or_zero]
    print(result)

# Example run
coin_toss()

Output example:

Tails

49. Add Two Matrices in Python

Matrices are arrays of numbers that are arranged in rows and columns.

To add two matrices, you need to perform element-wise addition as described here.

In Python, you can represent matrices with lists of lists (nested lists). In this case, you can implement the matrix addition with the following piece of code:

# A function that finds the sum of two matrices
def add_matrices(X, Y):
    l = len(X[0])
    h = len(X)
    return [[X[i][j] + Y[i][j] for j in range(l)] for i in range(h)]

# Example run
X = [
    [1,7,1],
    [4,2,1],
    [7,9,9]
]

Y = [
    [1,8,1],
    [9,0,3],
    [2,4,7]
]

# Print rows to make the output readable in the console
for r in add_matrices(X, Y):
   print(r)

Output:

[2, 15, 2]
[13, 2, 4]
[9, 13, 16]

In this implementation, the 5th row is a list comprehension for loop. It represents a nested for loop where each matrix row and column is iterated through.

50. Transpose a Matrix in Python

A matrix transpose means the matrix is flipped over its diagonal.

In other words, each position (i, j) is replaced with (j, i) in the matrix.

In Python, you can use nested lists to represent matrices. When doing this, you can compute a transpose for the matrix with the following code:

# A function that transposes a matrix
def transpose(X):
    l = len(X[0])
    h = len(X)
    return [[X[j][i] for j in range(h)] for i in range(l)]

# Example run
X = [
    [1,7,1],
    [4,2,1],
    [7,9,9]
]

# Print rows to make the output readable in the console
for r in transpose(X):
   print(r)

Output:

[1, 4, 7]
[7, 2, 9]
[1, 1, 9]

In this implementation, the 5th row is a list comprehension for loop. It represents a nested for loop where each matrix row and column is iterated through.

51. Multiply Two Matrices in Python

To multiple two matrices, you need to implement the matrix multiplication algorithm.

Matrix multiplication means:

  1. Take a row from matrix A and a column on matrix B.
  2. Multiply the corresponding elements by one another.
  3. Sum up the results of the multiplications.
  4. Add the result to the result matrix at a corresponding position.
  5. Repeat until no rows left.

An image is worth a thousand words, so here is one:

How to Multiply Matrices
Image Source: Math is fun

Here is how the algorithm looks in code:

# A function that multiplies two matrices
def multiply_matrices(X, Y):
    return [[sum(a * b for a, b in zip(X_row, Y_col)) for Y_col in zip(*Y)] for X_row in X]

# Example run
X = [
    [1,7,1],
    [4,2,1],
    [7,9,9]
]

Y = [
    [1,8,1],
    [9,0,3],
    [2,4,7]
]

# Print rows to make the output readable in the console
for r in multiply_matrices(X, Y):
   print(r)

Output:

[66, 12, 29]
[24, 36, 17]
[106, 92, 97]

In this implementation, the 3rd row is a list comprehension for loop. It is a nested loop where there are three inner for loops that implement the algorithm described above.

52. Track the Index in a For Loop

Sometimes when you perform a for loop, you wish there was an easy way to track the index of the current element. By default, this is not possible.

But using the built-in enumerate() function, you can relate each list element with an index.

This makes it easy for you to loop through the list and know the index at each loop.

Here is how it looks in code:

names = ["Alice", "Bob", "Charlie", "David"]

for index, name in enumerate(names):
    print(f"At position {index} is {name}")

Output:

At position 0 is Alice
At position 1 is Bob
At position 2 is Charlie
At position 3 is David

Learn more about enumerate() function in Python.

53. Flatten a Nested Python List

Given a list of lists, you can easily flatten the list to a 1D list with a for loop.

To do this:

  1. Loop through the list of lists.
  2. For each list, place each element in the list to a result list.
  3. Return the list.

Instead of using a nested for loop, you can use a one-liner list comprehension to make the code shorter. In case you find it hard to read, you can convert the comprehension back to a nested for loop.

Anyway, here is the implementation:

def flatten(nested_list):
    return [item for sublist in nested_list for item in sublist]

# Example run
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

numbers = flatten(matrix)

print(numbers)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

54. Convert String to Date in Python

Python has a built-in datetime module for dealing with date objects reliably.

The datetime module comes in with a datetime.strptime() function. You can use this to create a date object given a date as a string. To do this:

  1. Import the datetime from datetime.
  2. Create a date string in some format.
  3. Convert the string to a date object with the given format.

For example:

from datetime import datetime

date_time_str = '20/10/21 03:59:44'

date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')

print ("The date is", date_time_obj)

Output:

The date is 2021-10-20 03:59:44

55. Count the Frequency of Items in a List

To count the frequencies of list items in Python, you need to:

  1. Have a list full of elements.
  2. Create a frequency dictionary to map item -> item frequency.
  3. Loop through the list.
  4. On each element, increment its counter in the frequency dictionary.

Here is how it looks in code:

# A function that counts frequencies of the list items
def item_frequency(in_list):
    frequencies = {}
      
    for i in in_list:
        if i in frequencies:
            frequencies[i] += 1
        else:
            frequencies[i] = 1
    return frequencies

# Example run       
freqs = item_frequency(["Alice", "Bob", "Bob", "Charlie", "Bob"])

print(freqs)

Output:

{'Alice': 1, 'Bob': 3, 'Charlie': 1}

56. Add a Word to the End of an Existing File

To add a word to the end of an existing file:

  1. Open the file in write mode.
  2. Write a string to the file.
  3. Close the file.

You can use a context manager to open the file. This means you don’t have to worry about closing the file.

Given a list named example.txt with the following contents:

This is a test
The file contains a bunch of words
Bye!

You can write a new string to the end of it with a context manager like this:

with open("example.txt", "w") as file:
    file.write("A new string")

Output:

This is a test
The file contains a bunch of words
Bye!
A new string

57. Parse the File Extension from a File Name

To get the file extension from a path or file name, use the os.path.splitext function. This splits the file into two parts into a list:

  1. The path.
  2. The extension.

To get the extension, just access the second element of the list.

Here is how it looks in code:

import os.path

file = "example.py"
extension = os.path.splitext(file)[1]

print(f"The extension of file '{file}' is '{extension}'")

Output:

The extension of file 'example.py' is '.py'

58. Parse the File Name from the Path

To get the name of the file from a path, use os.path.basename() function.

For example:

import os

file_path = "Example/Directory/With/python_program.py"
file_name = os.path.basename(file_path)

print(file_name)

Output:

python_program

59. A Function That Takes a Default Argument

In Python, you can give function default arguments. This means you can call the function with or without an argument.

As this task does not state what kind of function to create, you can use your imagination.

For instance, let’s create a function greet() that says “Hello, there” by default. But once a name is given, the function greets the name.

Here is how:

def greet(name="there"):
    print(f"Hello, {name}!")
    
greet()
greet("Alice")

Output:

Hello, there!
Hello, Alice!

Learn more about default arguments in Python.

60. Count the Number of Files in the Present Directory

To count how many files are in the present directory, use os module.

  1. Use os.listdir(".") to list everything in the present directory.
  2. Call os.path.isfile() function for each item to verify it is a file.
  3. Return/print the result.
import os

print(len([file for file in os.listdir('.') if os.path.isfile(file)]))

Output:

9

61. Check the File Size in Python

To check the file size of a specific file, use the os.path.getsize() function.

For example:

import os

size = os.path.getsize("example.txt") 
print(f"The size of file is {size} bytes")

Output:

The size of file is 74 bytes

62. Calculate the Power of a Number

In Python, you can compute the power with the double-asterisk operator.

For example, 10^3 can be calculated with:

num = 10

power = num ** 3

print(power)

Output:

1000

63. Snake-Casify Strings in Python

Snake case means writing style where each blank space is replaced by an underscore _.

To create a Python program that converts a string into a snake case, replace each space with a “_”.

This is possible using the built-in replace() method of a string.

string = "This is a test"

snake = string.replace(" ", "_")

print(snake)

Output:

This_is_a_test

64. Camel-Casify Strings in Python

Camel case means writing style where there are no spaces between words. Instead, each word begins with a capital first letter and is connected to the next word.

To write a Python program that camel casifies a string:

  1. Split the words into a list by blank space.
  2. Convert each string into title case (first letter capital).
  3. Join the parts without spaces.

Here is how it looks:

# A program that converts a string to camel-case
def camel(string):
    words = string.split(" ")
    parts_upper = [word.title() for word in words]
    return "".join(parts_upper)

# Example run
string = "this is a test"
camel = camel(string)

print(camel)

Output:

ThisIsATest

65. Get All Combinations of a List

To get combinations of length r in a list, use itertools.combinations() function.

To get all the combinations of any length:

  1. Loop through numbers from 1 to the length of the list.
  2. Create a combination of the given length and add to the results list.

Here is a script that computes all combinations of list [1, 2, 3]:

import itertools
numbers = [1, 2, 3]

combinations = []
for r in range(len(numbers)+1):
    for combination in itertools.combinations(numbers, r):
        combinations.append(combination)

print(combinations)

Output:

[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

Learn more about combinations and powersets in Python.

66. Remove Duplicates from a List

To remove duplicates from a Python list:

  1. Have a list of items.
  2. Create an empty result list.
  3. Loop through the list of items.
  4. Add each item into the result list if it is not already there.
  5. Return the result.

Here is how it looks in code:

# A function that removes duplicates from a list
def de_dupe(items):
    result = []
    for item in items:
        if item not in result:
            result.append(item)
    return result


# Example run
numbers = [1, 2, 2, 2, 3, 1, 2, 5, 5]

de_duped_nums = de_dupe(numbers)

print(de_duped_nums)

Output:

[1, 2, 3, 5]

67. Python Program to Replace Characters of a String

Python string has a built-in method called replace().

This function takes two parameters:

  1. A character to be replaced.
  2. A character to be inserted.

You can use this method to replace the characters of that string.

For example, let’s replace all “s” characters with “z”:

sentence = "This is a test"

new_sentence = sentence.replace("s", "z")

print(new_sentence)

Output:

Thiz iz a tezt

68. Round Floats to Two Decimals

Python comes in with a built-in function round().

This function takes two arguments:

  1. A number to round.
  2. The number of desired decimal places.

The function rounds the number to the given decimal places.

For example, let’s round pi to 2 decimals:

from math import pi

print(f"Pi is {round(pi, 2)} when rounded to 2 decimals.")

Output:

Pi is 3.14 when rounded to 2 decimals.

69. Accept Any Number of Keyword Arguments

A keyword argument in Python is a function argument that has a name label attached to it.

An example call to a function with a keyword argument can look like this:

my_func(name="Jack")

Let’s for example implement a function that takes student info as its argument. You can give it as many keyword arguments as you wish. As a result, it prints the student’s data in a nicely formatted fashion.

Here is the example code:

# An example function that takes any number of keyword arguments
def info(**students):
    print("This year students info:")
    for name, major in students.items():
        print(f"- {name}: {major}")
    print("\n")

# Example run
info(Alice="Physics", Bob="Maths")

info(Alice="Applied Physics", Bob="Maths",
     Charlie="Pharmaseutics", David="Fluid Mechanics")

Output:

This year students info:
- Alice: Applied Physics
- Bob: Maths
- Charlie: Pharmaseutics
- David: Fluid Mechanics

Learn more about keyword arguments in Python.

70. Sum a List

To sum a list of numbers in Python:

  1. Initialize result at 0.
  2. Loop through the list of numbers.
  3. Add each number to the result.
  4. Return the result.

Here is the code:

# A function that calculates the sum of numbers
def total(numbers):
    result = 0
    for number in numbers:
        result += number
    return result


# Example run
numbers = [1, 2, 3, 4, 5]

sum = total(numbers)

print(sum)

Output:

15

71. Split a String

Python string has a built-in method called split(). This function takes one argument which is the delimiter according to which you want to split the string.

Here are some examples:

sentence = "This is a test. It demonstrates splitting strings."

split_by_spaces = sentence.split()
split_by_dot = sentence.split(".")
split_by_letter_s = sentence.split("s")

print(f"Split by spaces: {split_by_spaces}")
print(f"Split by dots: {split_by_dot}")
print(f"Split by letter 's': {split_by_letter_s}")

Output:

Split by spaces: ['This', 'is', 'a', 'test.', 'It', 'demonstrates', 'splitting', 'strings.']
Split by dots: ['This is a test', ' It demonstrates splitting strings', '']
Split by letter 's': ['Thi', ' i', ' a te', 't. It demon', 'trate', ' ', 'plitting ', 'tring', '.']

72. Get Current Time in Python

You can use Python’s built-in datetime module to obtain the current time.

To do this:

  1. Import the datetime from datetime module.
  2. Get the current date object.
  3. Grab the time from the current date in a specific format.

Here is how it looks in code:

from datetime import datetime

today_date = datetime.now()

time_now = today_date.strftime("%H:%M:%S")
print(f"The current time is {time_now}")

Output:

The current time is 09:35:26

73. Add Quotes in a String

To add quotation marks inside a string in Python, you have two options:

  1. Use double quotation marks as the string markers and single quotation marks as the quotes.
  2. Use single quotes as the string marker and double quotation marks as the quotes.

Here are both ways in code:

quote1 = "Then he said 'I will miss you'."
quote2 = 'Then he said "I will miss you".'

print(quote1)
print(quote2)

Output:

Then he said 'I will miss you'.
Then he said "I will miss you".

Learn more about quotes and strings in Python.

74. Document a Function Using a Docstring

In Python, you have a special syntax for documenting your code. This is called a docstring.

A docstring is a triple-quote string that can be spread across multiple lines.

The purpose of the docstring is to provide useful information about a function, class, or module. In Python, it is possible to call help() on any function, class, or module. When you do this, the docstring description is printed into the console.

Here is an example:

# Document a function with a docstring """ """
def add(a, b):
    """
    This function adds two numbers and returns the result.
        - a is an integer
        - b is an integer

        - res is the result
    """
    res = a + b
    return res


# Example use:
help(add)

Output:

Help on function add in module __main__:

add(a, b)
    This function adds two numbers and returns the result.
        - a is an integer
        - b is an integer
    
        - res is the result

Learn more about Python docstrings.

75. Python Program to Parse a JSON String

To convert a JSON object into a Python dictionary, use json.loads() function. Remember to import the json module before doing this.

Here is an example:

import json

# JSON string:
data_JSON = '{ "name": "John", "age": 23, "major": "Physics" }'

# JSON to Python Object (it becomes a dictionary)
data = json.loads(data_JSON)

# Use the data dict like any other dict in Python:
print(data["major"])

Output:

Physics

76. Generate a Textual Representation of an Object

When you print an object in Python, you may get a verbose result like this:

<__main__.Student object at 0x105a264c0>

But this is not readable and you can make no sense of it.

To fix this, implement a special method called __str__ in your class.

For example, let’s create a Student class. Furthermore, let’s make printing student objects produce a readable result by implementing the __str__ method.

class Student:
    def __init__(self, name, major):
        self.name = name
        self.major = major

    # String representation
    def __str__(self):
        return f"I am {self.name} and I study {self.major}"


# Example run
student = Student("Alice", "Chemistry")

print(student)

Output:

I am Alice and I study Chemistry

77. Read a File Into a List

To read a file into a list in Python:

  1. Open a file.
  2. Initialize an empty list to store the lines.
  3. Read the lines one by one and store each line to the list.
  4. Close the file.

A great way to deal with files is using context managers. A context manager auto-closes the file after being used. This saves you a little bit of overhead and lines of code. A context manager is used with the with statement.

Given a file called example.txt with the following contents:

This is a test
Let's read a file into Python
Let's see how it plays out...

You can read the lines in this file to a list with a context manager as follows:

with open("example.txt", "r") as file:
    lines = []
    for line in file.readlines():
        lines.append(line.strip("\n"))
    print(lines)

Output:

['This is a test', "Let's read a file into Python", "Let's see how it plays out..."]

78. Check If a Number Is an Armstrong Number

An Armstrong number is a number whose digits to the power of the length of the number equals the number.

For instance, 1634 is an Armstrong number because: 1^4 + 6^4 + 3^4 + 4^4.

To create a Python program to check if a given number is an Armstrong number:

  1. Have a target number.
  2. Initialize an empty sum.
  3. Go through each digit, raise it to the length power, and add to the result.
  4. Check if the result equals the original number.

Here is how it looks in code:

# A function that checks if a given number is an armstrong number
def is_armstrong(number):
    order = len(str(number))
    sum = 0
    temp = number
    while temp > 0:
        digit = temp % 10
        sum += digit ** order
        temp //= 10
    if number == sum:
        print(f"{number} is an Armstrong number")
    else:
        print(f"{number} is not an Armstrong number")


# Example run
print(is_armstrong(1634))

Output:

1634 is an Armstrong number

79. Capitalize a String

Python string comes with a built-in upper() method. This method capitalizes the whole string.

For example:

name = "alice"

name_cap = name.upper()

print(name_cap)

Output:

ALICE

80. Break Out of a For Loop

Breaking a loop means jumping out of a loop before the loop is exhausted.

Here is an example of a function that checks if the number matches the target. When it does, the loop is escaped:

def find(target):
    for number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
        print(f"{number} in inspection...")
        if number == target:
            print("Target found!")
            break


find(3)

Output:

1 in inspection...
2 in inspection...
3 in inspection...
Target found!

Learn more about the break and other control flow statements here.

81. Check a Condition with One Line of Code

In Python, you can replace short if-else statements with one-liners. This is possible using a ternary conditional operator.

Here is an example of how:

age = 20

age_group = "adult" if age >= 18 else "minor"

print(age_group)

Output:

adult

Learn more about one-liner conditional operators in Python.

82. Calculate Remainder in Division

In Python, you can use the % operator to calculate the remainder in the division.

For example, dividing 11 slices of pizza with 3 guests means 2 leftover slices.

pizza_slices = 11
participants = 3

left_overs = pizza_slices % participants

print(f"{left_overs} slices are left over.")

Output:

2 slices are left over.

Learn more about remainders and modulo in Python.

83. Unpack a List to Separate Variables

In Python, it is possible to unpack iterables.

This means you can tear apart iterables to separate variables by comma separating the variables and using assignment operator on the iterable.

For example:

numbers = [1, 2, 3]

x, y, z = numbers

print(x)
print(y)
print(z)

Output:

1
2
3

84. Square a List of Numbers

To square a list of numbers in Python:

  1. Have a list of numbers.
  2. Initialize an empty result list.
  3. Loop through each number.
  4. Raise each number to the second power.
  5. Add the result into the result list.

Here is how it looks in code:

# A function that squares a list of numbers
def square(numbers):
    result = []
    for number in numbers:
        result.append(number ** 2)
    return result


# Example run
numbers = [1, 2, 3]
squared = square(numbers)
print(squared)

Output:

[1, 4, 9]

85. Filter Even Numbers

To filter even numbers in Python:

  1. Have a list of numbers.
  2. Initialize an empty result list.
  3. Loop through each number.
  4. Check if the number is even.
  5. Add the result into the result list.

Here is how it looks in code:

# A function that filters even numbers
def filter_even(numbers):
    result = []
    for number in numbers:
        if number % 2 == 0:
            result.append(number)
    return result


# Example run
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_nums = filter_even(numbers)

print(even_nums)

Output:

[2, 4, 6, 8, 10]

Learn more about list filtering in Python here.

86. Join Two or More Strings

Python string comes with a built-in join() method.

This function takes one argument, which is the separator character.

For example, to join strings with an empty space as a separator:

s1 = "This"
s2 = "is"
s3 = "a test"

sentence = " ".join([s1, s2, s3])

print(sentence)

Output:

This is a test

Learn more about joining strings and other string methods from here.

87. Remove Specific Values from a List

You can use the filter() function to filter out values based on a criterion.

The filter() function takes two arguments:

  1. A filtering function. This is usually a lambda expression.
  2. An iterable, such as a list to be filtered.

The filter() function applies the filtering function on each element of the list to produce the result.

For example, let’s filter out integers from a list:

items = ["Alice", 2, 3, "Bob", "Charlie", 30]

# Let's remove numbers

names = filter(lambda x: not isinstance(x, int), items)

print(list(names))

Output:

['Alice', 'Bob', 'Charlie']

88. Add Values to the Beginning of a List

Python list has a built-in method insert(). It takes two arguments:

  1. A target index.
  2. A string to be placed into the target index.

You can use the insert() method to add an element to the beginning of a list.

For example:

names = ["Bob", "Charlie", "David"]

names.insert(0, "Alice")

print(names)

Output:

['Alice', 'Bob', 'Charlie', 'David']

Learn more about adding and removing values from Python lists here.

89. Calculate HCF in Python

The Highest Common Factor (HCF) of two numbers is the highest number that evenly divides both numbers.

For example, the HCF of 12 and 36 is 12.

To calculate the HCF in Python:

  1. Take two numbers.
  2. Determine the smallest number of the two.
  3. Loop through numbers from 1 to the smallest number.
  4. Check on each value if it factors the greatest number.
  5. Keep track of the highest such number.
  6. At the end of the loop, return the highest factor.

Here is a Python program to find the HCF between two numbers:

# A function that finds the HCF
def compute_hcf(x, y):
    if x > y:
        smaller = y
    else:
        smaller = x
    for i in range(1, smaller + 1):
        if x % i == 0 and y % i == 0:
            hcf = i
    return hcf


# Example run
n1 = 81
n2 = 36
print(f"The H.C.F. between {n1} and {n2} is {compute_hcf(81, 36)}")

Output:

The H.C.F. between 81 and 36 is 9

90. Show N Fibonacci Numbers

A Fibonacci sequence is a series of numbers where the next number is the sum of the previous two.

For example, 0,1,1,2,3,5,8,13,21,34.

To find a Fibonacci sequence of length n in Python:

# A function to print a fibonacci sequence
def show_fib(n_terms):
    n1, n2 = 0, 1
    count = 0
    if n_terms <= 0:
        print("Enter a positive integer")
    else:
        print("Fibonacci sequence:")
        while count < n_terms:
            print(n1)
            nth = n1 + n2
            n1 = n2
            n2 = nth
            count += 1


# Example run
show_fib(10)

Output:

0
1
1
2
3
5
8
13
21
34

91. Python Program to Calculate Age

To calculate the age given a date object in Python:

  1. Subtract the beginning year from the current year.
  2. Remove 0 if the month/day of the beginning date precedes the current month/day.

Here is how it looks in code:

from datetime import date


def age(birthdate):
    today = date.today()
    age = today.year - birthdate.year - \
        ((today.month, today.day) < (birthdate.month, birthdate.day))
    return age


birthdate = date(1996, 2, 27)

print(f"With birth date of {birthdate}, you are {age(birthdate)} years old")

Output:

With birth date of 1996-02-27, you are 25 years old

The above program knows how to handle leap years too. Check out this article to learn more.

92. Simulate Throwing a Dice in Python

When you throw a dice, you get 1, 2, 3, 4, 5, or 6.

To simulate dice toss in Python, randomize a number between 1 and 6. You can achieve this using the random module’s randint() function.

Here is how it looks in code:

from random import randint

def throw_dice():
    return randint(1, 6)

print(throw_dice())

Output example:

2

93. Find Out How Far Is the Horizon

This involves a bit of basic trigonometry.

To calculate the distance to the horizon, you need to realize the horizon distance is the “opposite” a side of a right triangle formed by:

  1. Earth’s radius + your height.
  2. Earth’s radius.
  3. The distance to the horizon.
How far is the horizon

Here is how you can implement the equation in your Python program:

from math import sqrt

# A function that calculates distance to horizon in meters given height in meters
def horizon_distance(h):
    R = 6_371_000
    return sqrt(2 * R * h + h ** 2)


airplane_height = 12_000
d_horizon = horizon_distance(airplane_height)
print(
    f"You can see ~{round(d_horizon / 1000)}km from a commercial flight.")

Output:

You can see ~391km from a commercial flight.

94. Calculate Area of a Circle

The area of a circle is given by A = pi * r^2.

To write a Python program to calculate the area of a circle, import pi from math module and calculate the area with the above formula:

from math import pi

# A function to find the area of a circle
def circle_area(r):
    return pi * r ** 2

radius = 5

print(f"A circle of radius {radius} takes {circle_area(radius)} square meters of space.")

Output:

A circle of radius 5 takes 78.53981633974483 square meters of space.

95. Find the Volume of a Cube

Given a cube of side length a, the volume V = a^3.

Here is a Python code example on how to calculate the volume of a cube:

from math import pi

# A function to find the volume of a cube
def volume_cube(s):
    return s ** 3


side = 5

print(f"A cube of sides {side} takes {volume_cube(side)} cubic meters of room.")

Output:

A cube of sides 5 takes 125 cubic meters of room.

96. Measure Elapsed Time

To measure the runtime of a program, import the time module into your project and:

  1. Store the start time into memory.
  2. Run a piece of code.
  3. Store the end time into memory.
  4. Calculate the time difference between the start and end.

Here is how it looks in code:

import time

# Example function that takes some time
def sum_to_million():
    sum = 0
    for i in range(1_000_000):
        sum += i


# Let's see how long summing numbers up to one million takes in Python:
start = time.time()
sum_to_million()
end = time.time()

# Not too long...
print(f"The time to sum numbers up to million took {end - start} seconds")

Output:

The time to sum numbers up to million took 0.06786799430847168 seconds

97. Check If a Set Is a Subset of Another Set in Python

In set theory, set A is a subset of B if all the elements in set A are also in set B.

In Python, you can use the built-in issubset() method to check if a set A is a subset of set B.

For example:

A = {1, 2, 3}
B = {1, 2, 3, 4, 5, 6}

print(A.issubset(B))

Output:

True

Learn more about sets and the issubset() method here.

98. Find N Longest Strings in a Python List

To find n longest strings in a list:

  1. Sort the list of strings based on length.
  2. Pick the n last elements of the sorted list. These are the longest strings.

Here is how it looks in code:

# A function that finds n longest words in a list of strings
def find_longest(strings, n):
    l = len(strings)
    # If n is more or equal to the list length, return the whole list.
    if n >= l:
        return strings
    else:
        sorted_strings = sorted(strings, key=len)
        return sorted_strings[-n:]


# Example run
names = ["Alice", "Bob", "Charlie", "David", "Emmanuel", "Frank", "Gabriel"]

print(find_longest(names, 3))

Output:

['Charlie', 'Gabriel', 'Emmanuel']

99. Clone a Python List Independently

To take an independent copy of a list, use the deepcopy() method from the copy module.

For example:

import copy

names = ["Alice", "Bob", "Charlie"]

names_clone = names.deepcopy()

print(names_clone)

Output:

['Alice', 'Bob', 'Charlie']

Read more about copying lists in Python.

100. Break List Into N-Sized Chunks

If you want to break. alist into n-sized chunks:

  1. Create an empty result list.
  2. Loop through the original list by taking the chunk-sized steps.
  3. At each step, add the current element and the next i elements to the result list.
  4. When there are no values left, return the list.

Here is how it looks in code:

# A program that groups a list into chunks
def chunks(elements, chunk_size):
    result = []
    for i in range(0, len(elements), chunk_size):
        result.append(elements[i:i + chunk_size])
    return result


# Example run
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

parts = chunks(numbers, 4)

print(parts)

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

Conclusion

That is a lot of Python examples. I hope you find it useful where ever you go.

Happy coding my friends!

Further Reading

Python Tricks

How to Write to a File in Python

The with Statement in Python

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.