Python String

Python String Tutorials

Introduction:

A string is a sequence of characters. In Python, you can define a string using either single quotes () or double quotes (), or triple quotes (”’ or “””) for multiline strings. Here are some examples:

Python string features:

  1. Immutable: Strings in Python are immutable, meaning that once a string is created, its contents cannot be changed. If you want to modify a string, you need to create a new string with the desired changes.
  2. Sequence of Characters: Strings are a sequence of individual characters. Each character in a string is assigned an index, starting from 0 for the first character. This allows you to access and manipulate specific characters within a string using indexing and slicing operations.
  3. Unicode Support: Python strings support Unicode, allowing you to work with characters from different languages, including non-ASCII characters. This enables you to handle and process text in various encodings and writing systems.
  4. Concatenation: Strings can be concatenated using the “+” operator, allowing you to combine multiple strings into a single string. For example, “Hello” + ” ” + “World” results in the string “Hello World”.
  5. Length: You can obtain the length of a string using the `len()` function, which returns the number of characters in the string. This is useful for determining the size of a string or iterating over its characters.
  6. String Formatting: Python provides various methods for formatting strings. This includes the use of placeholders or format specifiers, such as `%` operator or the `format()` method, to insert variables or values into a string with specified formatting.
  7. String Operations and Methods: Python offers a wide range of built-in operations and methods specifically designed for working with strings. These include operations like string concatenation, repetition, and membership checks, as well as methods for case conversion, substring searching, replacing, splitting, stripping, and more.
  8. Escape Sequences: Strings in Python support escape sequences, which allow you to include special characters that are difficult to type directly. For example, using `n` represents a newline character, `t` represents a tab character, and `”` represents a double quote character within a string.
  9. String Comparison: Strings can be compared using operators such as `==`, `!=`, `<`, `>`, `<=`, and `>=`. Comparison is performed based on lexicographic (dictionary) ordering of characters, which compares each corresponding character’s Unicode value.
  10. String Iteration: Python allows you to iterate over a string using loops, enabling you to process each character individually or perform operations on the entire string.

Python string advantages:

  1. Versatility: Python strings are versatile and widely used for handling and manipulating text-based data. They can store and process alphanumeric characters, symbols, and even Unicode characters, making them suitable for various applications and internationalization needs.
  2. Immutable Nature: Python strings are immutable, meaning their contents cannot be changed once they are created. This immutability ensures the integrity of strings and prevents accidental modifications, making them reliable for operations like string matching, hashing, or as keys in dictionaries.
  3. Extensive String Methods: Python provides a rich set of built-in string methods that offer a wide range of operations. These methods allow you to perform tasks like searching, replacing, splitting, joining, formatting, case conversion, and more. The extensive set of string methods simplifies complex string manipulation tasks and saves you time and effort.
  4. Unicode Support: Python strings have excellent support for Unicode, making them capable of representing characters from various writing systems, including non-ASCII characters. This allows you to work with and process text in different languages and encodings, making Python strings suitable for internationalization and multilingual applications.
  5. String Formatting: Python offers flexible and powerful string formatting capabilities. With techniques like the `%` operator or the `format()` method, you can easily insert variables or values into a string with specified formatting. This makes it convenient for generating dynamic strings, constructing messages, or formatting output.
  6. String Interpolation: Python 3.6 and later versions introduce f-strings, which provide a concise and readable way to embed expressions within string literals. This feature, known as string interpolation, simplifies the process of combining variables and expressions with strings, improving code readability and reducing the need for concatenation.
  7. Compatibility with File Operations: Python strings integrate seamlessly with file handling operations. You can read or write strings to files, manipulate file paths as strings, and use string methods to parse or manipulate file content. This compatibility makes it easier to work with text files and perform file-related operations.
  8. Regular Expressions: Python’s `re` module offers support for regular expressions, providing powerful pattern matching and text manipulation capabilities. Regular expressions allow you to search for specific patterns, extract information, or perform complex text transformations, making them valuable for tasks like data validation, parsing, and text processing.
  9. Consistency and Familiarity: Python strings follow consistent syntax and behavior across different operations and methods. This consistency, combined with Python’s focus on readability and simplicity, makes working with strings in Python intuitive and easy for developers who are familiar with the language.
  10. Extensive Community and Documentation: Python is a widely adopted programming language, and as a result, there is a vast community of developers and extensive documentation available for working with strings. You can find libraries, tutorials, and resources to help with advanced string manipulation, handling special cases, or optimizing string-related operations.

Python string disadvantages:

  1. Immutability: While immutability can be an advantage in terms of data integrity, it can also be a disadvantage when it comes to efficiency. Since strings are immutable, any operation that involves modifying a string, such as concatenation or replacing characters, requires creating a new string object. This can be inefficient, especially when dealing with large strings or performing many operations.
  2. Memory Overhead: Each individual character in a Python string requires memory to store its Unicode value and other metadata. This fixed overhead per character can consume significant memory, especially when working with large strings or processing large amounts of text data. In scenarios with memory constraints, this overhead can become a limiting factor.
  3. Difficulty with Mutable Operations: Some string manipulation tasks, such as inserting or removing characters at specific positions, can be cumbersome and inefficient due to the immutability of strings. Achieving such operations often requires creating new string objects or converting the string to a mutable data structure like a list, performing the operation, and then converting it back to a string.
  4. Comparison Complexity: Comparing strings for equality or sorting them can have time complexity proportional to the length of the strings being compared. In cases where string comparison or sorting is a critical performance factor, more efficient data structures or algorithms, like tries or radix sort, might be more suitable.
  5. Limited Unicode Support in Older Versions: While Python has excellent Unicode support, there were limitations in earlier versions (pre-Python 3) regarding Unicode handling. Older versions required explicit encoding and decoding operations when working with non-ASCII characters, which could be a source of confusion or errors.
  6. Limited Mutable String Options: While Python strings are immutable, there may be scenarios where mutable string operations are desired. Python’s built-in string methods offer limited options for in-place modification, and workarounds like converting the string to a list and back can introduce additional complexity and potential performance drawbacks.
  7. Difficulty with Low-Level Operations: Python strings abstract away low-level memory access and manipulation, which can be advantageous for most applications. However, in certain scenarios where direct byte-level or bit-level manipulation is required, Python strings may not be the most suitable data structure, and using other byte-oriented data types or libraries may be more appropriate.
  8. Performance in Heavy String Manipulation: For scenarios that involve heavy string manipulation, such as text parsing or processing large volumes of text data, Python strings may not offer the best performance. In such cases, lower-level languages or specialized text processing libraries may provide more efficient options.

Re-assign Strings:

In Python, you can reassign a string to a new value by simply assigning the new value to the variable that holds the string.  Here’s an example:

# Initial string assignment
my_string = "Hello, World!"
print("Original string:", my_string)

# Reassigning the string to a new value
my_string = "Welcome to Python!"
print("Reassigned string:", my_string)

In the example above, the first print statement outputs “Hello, World!” because my_string is initially assigned that value. Then, my_string is reassigned to “Sqatools” and the second print statement outputs the new value.

It’s important to note that strings are immutable in Python, which means that once you create a string, you cannot modify it. When you “modify” a string by, for example, concatenating two strings or removing a character, you are actually creating a new string object. Here are some examples:

# Example to demonstrate string immutability in Python

# 1. String Concatenation
greeting = "Hello"
new_greeting = greeting + ", World!"
print("Original string (after concatenation):", greeting) # Output: Hello
print("New string (concatenation result):", new_greeting) # Output: Hello, World!

# 2. String Replacement
my_string = "Hello, Python!"
new_string = my_string.replace("Python", "World")
print("\nOriginal string (after replacement):", my_string) # Output: Hello, Python!
print("New string (replacement result):", new_string) # Output: Hello, World!

# 3. String Slicing
text = "Immutable"
sliced_text = text[:3] # Taking the first three characters
print("\nOriginal string (after slicing):", text) # Output: Immutable
print("Sliced string (slicing result):", sliced_text) # Output: Imm

Deleting string:

In Python, you cannot delete individual characters in a string because strings are immutable. However, you can delete the entire string object from memory using the del statement.  Here’s an example:

In the example above, the first print statement outputs the value of my_string, which is “Hello, World!”. Then, the del statement deletes the my_string object from memory. When we try to print my_string again, we get a NameError because the variable no longer exists.

String formatting methods:

Python provides several methods for formatting strings. Here are the most commonly used methods:

  1. The % operator: This operator allows you to format strings using placeholders, which are replaced with values at runtime. Here’s an example:
# Using the % operator for string formatting
name = "Alice"
age = 25

formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, %s and %d are placeholders for the name and age variables, respectively. The values of these variables are provided in a tuple that follows the % operator.

  1. The str.format() method: This method allows you to format strings using placeholders that are enclosed in curly braces. Here’s an example:
# Using the str.format() method for string formatting
name = "Alice"
age = 25

formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, {} is a placeholder for the name and age variables. The values of these variables are provided as arguments to the str.format() method.

  1. F-strings: It allows you to embed expressions inside placeholders that are enclosed in curly braces preceded by the f character. Here’s an example:
# Using f-strings for string formatting
name = "Alice"
age = 25

# Embedding variables directly into the string
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, the f character before the string indicates that it is an f-string. The expressions inside the curly braces are evaluated at runtime and the resulting values are inserted into the string.

String operator:

In Python, strings support several operators that can be used to perform various operations on strings. Here are some of the most commonly used string operators:

  1. Concatenation (+): The + operator can be used to concatenate two or more strings. Here’s an example:
# Using the + operator to concatenate strings
str1 = "Hello"
str2 = "World"
combined_str = str1 + " " + str2 # Adding a space between the words

print(combined_str)
# Output: Hello World
  1. Repetition (*): The * operator can be used to repeat a string a certain number of times. Here’s an example:
# Using the * operator to repeat a string
str1 = "Hello "
repeated_str = str1 * 3 # Repeating the string 3 times

print(repeated_str)
# Output: Hello Hello Hello
  1. Membership (in): The in operator can be used to check if a substring exists within a string. It returns True if the substring is found, and False otherwise. Here’s an example:
# Using the 'in' operator to check membership
sentence = "Python is awesome!"

# Checking if a substring exists within the string
substring = "Python"
result = substring in sentence

print(result)
# Output: True
  1. Indexing ([]): The [] operator can be used to access individual characters within a string. You can use a positive index to access characters from the beginning of the string, and a negative index to access characters from the end of the string. Here’s an example:
# Using the [] operator for indexing a string
my_string = "Python"

# Accessing characters using positive indices
first_char = my_string[0] # First character
last_char = my_string[5] # Last character (index 5 for "n")

print("First character:", first_char) # Output: P
print("Last character:", last_char) # Output: n

# Accessing characters using negative indices
second_last_char = my_string[-2] # Second last character (index -2 for "o")
print("Second last character:", second_last_char) # Output: o
  1. Slicing ([start:end]): The [] operator can also be used to extract a substring (or slice) from a string. The start argument specifies the starting index of the slice (inclusive), and the end argument specifies the ending index of the slice (exclusive). Here’s an example:
# Using the [] operator for string slicing
my_string = "Python Programming"

# Extracting a substring using slicing
substring = my_string[0:6] # From index 0 to 5 (6 is exclusive)
print(substring) # Output: Python
  1. Comparison (==, !=, <, <=, >, >=): The comparison operators can be used to compare two strings alphabetically. The == operator returns True if the two strings are equal, and False otherwise. The != operator returns True if the two strings are not equal, and False otherwise. The < and > operators return True if the left string is alphabetically less than or greater than the right string, respectively. The <= and >= operators return True if the left string is alphabetically less than or equal to or greater than or equal to the right string, respectively. Here’s an example:
# Comparison of strings using various operators
string1 = "Apple"
string2 = "Banana"

# Checking if the strings are equal
print(string1 == string2) # Output: False

# Checking if the strings are not equal
print(string1 != string2) # Output: True

# Checking if string1 is alphabetically less than string2
print(string1 < string2) # Output: True

# Checking if string1 is alphabetically greater than string2
print(string1 > string2) # Output: False

# Checking if string1 is alphabetically less than or equal to string2
print(string1 <= string2) # Output: True

# Checking if string1 is alphabetically greater than or equal to string2
print(string1 >= string2) # Output: False

String indexing and slicing:

Indexing:

Indexing: Each character in a string is assigned an index starting from 0. You can access a particular character in a string using its index. Here’s an example:

# Using indexing to access characters in a string
my_string = "Python"

# Accessing individual characters using their indices
first_char = my_string[0] # First character
second_char = my_string[1] # Second character
last_char = my_string[5] # Last character

print("First character:", first_char) # Output: P
print("Second character:", second_char) # Output: y
print("Last character:", last_char) # Output: n
Slicing:

You can extract a portion of a string using slicing. Slicing is done using the [] operator, with two indices separated by a colon (:) inside the brackets. Here’s an example:

# Using slicing to extract a portion of a string
my_string = "Python Programming"

# Slicing from index 0 to 6 (exclusive of index 6)
substring = my_string[0:6] # This gives 'Python'

print(substring) # Output: Python

In the example above, my_string[0:5] returns the first five characters of the string, my_string[:5] returns all the characters up to the fifth character, and my_string[-5:] returns the characters from the fifth-last to the last character.

Note that the first index in a slice is inclusive and the second index is exclusive. So, my_string[0:5] returns characters from index 0 to index 4, but not the character at index 5.

In addition to the two indices separated by a colon, you can also add a third index to specify the step value. Here’s an example:

# Using slicing with a step
my_string = "Python Programming"

# Extracting every second character from index 0 to index 12
substring = my_string[0:13:2] # From index 0 to 12, taking every second character

print(substring) # Output: Pto rg

String functions:

  1. `len()`: Returns the length of a string. Here’s an example:
# Using len() to get the length of a string
my_string = "Python Programming"

# Get the length of the string
length = len(my_string)

print("The length of the string is:", length) # Output: 18
  1. `lower()`: Converts all characters in a string to lowercase. Here’s an example:
# Using lower() to convert string to lowercase
my_string = "Python Programming"

# Convert the string to lowercase
lowercase_string = my_string.lower()

print("Original string:", my_string) # Output: Python Programming
print("Lowercase string:", lowercase_string) # Output: python programming
  1. `upper()`: Converts all characters in a string to uppercase. Here’s an example:
# Using upper() to convert string to uppercase
my_string = "Python Programming"

# Convert the string to uppercase
uppercase_string = my_string.upper()

print("Original string:", my_string) # Output: Python Programming
print("Uppercase string:", uppercase_string) # Output: PYTHON PROGRAMMING
  1. `title()`: Capitalizes the first character of each word in a string. Here’s an example:
# Using title() to capitalize the first character of each word
my_string = "python programming is fun"

# Convert the string to title case
title_string = my_string.title()

print("Original string:", my_string) # Output: python programming is fun
print("Title case string:", title_string) # Output: Python Programming Is Fun
  1. `capitalize()`: Capitalizes the first character of a string. Here’s an example:
# Using capitalize() to capitalize the first character of a string
my_string = "python programming"

# Capitalize the first character
capitalized_string = my_string.capitalize()

print("Original string:", my_string) # Output: python programming
print("Capitalized string:", capitalized_string) # Output: Python programming
  1. `swapcase()`: Swaps the case of all characters in a string. Here’s an example:
# Using swapcase() to swap the case of all characters in a string
my_string = "Python Programming"

# Swap the case of all characters
swapped_string = my_string.swapcase()

print("Original string:", my_string) # Output: Python Programming
print("Swapped case string:", swapped_string) # Output: pYTHON pROGRAMMING
  1. `count()`: Returns the number of occurrences of a substring in a string. Here’s an example:
# Using count() to count occurrences of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Count the occurrences of the word "Python"
count_python = my_string.count("Python")

print("Occurrences of 'Python':", count_python) # Output: 2
  1. `find()`: Returns the index of the first occurrence of a substring in a string. Here’s an example:
# Using find() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.find("Python")

print("Index of 'Python':", index_python) # Output: 0
  1. `rfind()`: Returns the index of the last occurrence of a substring in a string.
# Using rfind() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rfind("Python")

print("Index of the last 'Python':", last_index_python) # Output: 36

       10. `index()`: Like `find()`, but raises a `ValueError` if the substring is not found.

# Using index() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.index("Python")

print("Index of 'Python':", index_python) # Output: 0
  1. `rindex()`: Like `rfind()`, but raises a `ValueError` if the substring is not found.
# Using rindex() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rindex("Python")

print("Index of the last 'Python':", last_index_python) # Output: 36
  1. `startswith()`: Returns `True` if a string starts with a specified prefix, otherwise `False`.
# Using startswith() to check if the string starts with a specified prefix
my_string = "Python programming is fun."

# Check if the string starts with "Python"
starts_with_python = my_string.startswith("Python")

print("Starts with 'Python':", starts_with_python) # Output: True
  1. `endswith()`: Returns `True` if a string ends with a specified suffix, otherwise `False`.
# Using endswith() to check if the string ends with a specified suffix
my_string = "Python programming is fun."

# Check if the string ends with "fun."
ends_with_fun = my_string.endswith("fun.")

print("Ends with 'fun.':", ends_with_fun) # Output: True
  1. `replace()`: Replaces all occurrences of a substring with another substring.
# Using replace() to replace all occurrences of a substring
my_string = "Python is fun. Python is awesome."

# Replace "Python" with "Java"
new_string = my_string.replace("Python", "Java")

print("Original string:", my_string)
print("New string:", new_string)

       15. `strip()`: Removes whitespace (or other characters) from the beginning and end of a string.





  1. `rstrip()`: Removes whitespace (or other characters) from the end of a string.
# Using rstrip() to remove trailing whitespace
my_string = "Hello, world! "

# Remove the trailing whitespace
new_string = my_string.rstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. `lstrip()`: Removes whitespace (or other characters) from the beginning of a string.
# Using lstrip() to remove leading whitespace
my_string = " Hello, world!"

# Remove the leading whitespace
new_string = my_string.lstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. `split()`: Splits a string into a list of substrings using a specified delimiter.
# Using split() to split a string into a list of words
my_string = "Python is fun!"

# Split the string by whitespace (default behavior)
words = my_string.split()

print("List of words:", words)
  1. `rsplit()`: Splits a string from the right into a list of substrings using a specified delimiter.
# Using rsplit() to split a string from the right
my_string = "Python is fun and Python is awesome"

# Split the string by whitespace from the right
words = my_string.rsplit()

print("List of words:", words)

The separator used is the comma, which is passed as an argument to the rsplit() method. The 1 argument is used to specify that only one splitting should occur, which in this case splits the last fruit from the first two. Finally, we print the list of fruits.

       20. `join()`: Joins a list of strings into a single string using a specified delimiter.

# Joining with a space
words = ["Hello", "world", "Python", "rocks!"]
sentence = " ".join(words)
print(sentence) # Output: "Hello world Python rocks!"

# Joining with a comma
items = ["apple", "banana", "cherry"]
csv_line = ",".join(items)
print(csv_line) # Output: "apple,banana,cherry"

# Joining with a hyphen
letters = ["a", "b", "c", "d"]
hyphenated = "-".join(letters)
print(hyphenated) # Output: "a-b-c-d"
  1. `isalnum()`: Returns `True` if a string contains only alphanumeric characters, otherwise `False`.
# String with only letters and numbers
print("Hello123".isalnum()) # Output: True

# String with only letters
print("Python".isalnum()) # Output: True

# String with only numbers
print("2024".isalnum()) # Output: True

# String with a space
print("Hello World".isalnum()) # Output: False

# String with special characters
print("Hello@123".isalnum()) # Output: False

# Empty string
print("".isalnum()) # Output: False
  1. `isalpha()`: Returns `True` if a string contains only alphabetic characters, otherwise `False`.
# String with only letters
print("Python".isalpha()) # Output: True

# String with a space
print("Hello World".isalpha()) # Output: False

# String with numbers
print("Python3".isalpha()) # Output: False

# String with special characters
print("Hello!".isalpha()) # Output: False

# Empty string
print("".isalpha()) # Output: False

  1. `isdigit()`: Returns `True` if a string contains only digits, otherwise `False`.
# String with only digits
print("12345".isdigit()) # Output: True

# String with letters
print("123abc".isdigit()) # Output: False

# String with a space
print("123 456".isdigit()) # Output: False

# Empty string
print("".isdigit()) # Output: False
  1. `islower()`: Returns `True` if all characters in a string are lowercase, otherwise `False`.
# All lowercase letters
print("hello".islower()) # Output: True

# Mixed case
print("Hello".islower()) # Output: False

# Digits and special characters are ignored
print("hello123!".islower()) # Output: True

# Contains an uppercase letter
print("helloWorld".islower()) # Output: False

# Empty string
print("".islower()) # Output: False

      25. `isupper()`: Returns `True` if all characters in a string are uppercase, otherwise `False`.

# All uppercase letters
print("HELLO".isupper()) # Output: True

# Mixed case
print("Hello".isupper()) # Output: False

# Includes digits and symbols
print("HELLO123!".isupper()) # Output: True

# Contains a lowercase letter
print("HELLOworld".isupper()) # Output: False

# Empty string
print("".isupper()) # Output: False
  1. `istitle()`: Returns `True` if a string is titlecased (i.e., the first character of each word is capitalized), otherwise `False`.
# Title-cased string
print("Hello World".istitle()) # Output: True

# Mixed case
print("Hello world".istitle()) # Output: False

# Uppercase string
print("HELLO WORLD".istitle()) # Output: False

# Lowercase string
print("hello world".istitle()) # Output: False

# Single title-cased word
print("Python".istitle()) # Output: True
  1. `isspace()`: Returns `True` if a string contains only whitespace characters, otherwise `False`.
# Only spaces
print(" ".isspace()) # Output: True

# Only tabs
print("\t\t".isspace()) # Output: True

# Newline characters
print("\n\n".isspace()) # Output: True

# Mixed whitespace characters
print(" \t\n".isspace()) # Output: True

# Empty string
print("".isspace()) # Output: False
  1. `maketrans()`: Creates a translation table to be used with the `translate()` function.
# Mapping characters 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
  1. `translate()`: Returns a copy of a string with specified characters replaced.
# Create a translation table to replace 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
  1. `zfill()`: Pads a numeric string with zeros on the left until the specified width is reached.
# Example using zfill() to pad a string with leading zeros
number = "42"
padded_number = number.zfill(5)

print(padded_number) # Output: '00042'
  1. `expandtabs()`: Replaces tabs in a string with spaces.
# Example using expandtabs() to replace tabs with spaces
text = "Hello\tWorld\tPython"
expanded_text = text.expandtabs(4) # Replaces tabs with 4 spaces

print(expanded_text) # Output: 'Hello World Python'
  1. `encode()`: Encodes a string using a specified encoding.
# Encoding a string using UTF-8
my_string = "hello world"
encoded_string = my_string.encode("utf-8")

print(encoded_string) # Output: b'hello world'

In the example above, we have a string containing the phrase “hello world”. We then use the encode() method to encode the string using the UTF-8 encoding. The resulting encoded string is a bytes object, which is denoted by the “b” prefix in the output.

  1. `format_map()`: Formats a string using a dictionary.
# Using format_map() to format a string using a dictionary
person = {"name": "Alice", "age": 30}

# Format string using the dictionary
formatted_string = "My name is {name} and I am {age} years old.".format_map(person)

print(formatted_string)
  1. `isdecimal()`: Returns `True` if a string contains only decimal characters, otherwise `False`.
# Using isdecimal() to check if a string contains only decimal characters
my_string = "12345"

# Check if the string contains only decimal characters
is_decimal = my_string.isdecimal()

print(is_decimal) # Output: True
  1. `isnumeric()`: Returns `True` if a string contains only numeric characters, otherwise `False`.
# Using isnumeric() to check if a string contains only numeric characters
my_string = "12345"

# Check if the string is numeric
is_numeric = my_string.isnumeric()

print(is_numeric) # Output: True
  1. `partition()`:It split the string into parts based on the first occurrence of the substring.
# Using partition() to split a string based on the first occurrence of a substring
my_string = "Hello, world! Welcome to Python."

# Split the string at the first occurrence of ","
result = my_string.partition(",")

print(result)

Python Conditional Statements

Introduction:

In Python, the if-else statement allows you to execute different blocks of code based on certain conditions. It provides a way to make decisions and control the flow of your program.

The basic syntax of an if-else statement in Python is as follows:

if condition:
    # Code block to execute if the condition is True
else:
    # Code block to execute if the condition is False

The condition is an expression that evaluates to either True or False. If the condition is True, the code block immediately following the if statement will be executed. Otherwise, if the condition is False, the code block following the else statement will be executed.

Let’s look at an example to understand it better. Suppose we want to check whether a given number is positive or negative:

number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")
else:
    print("The number is negative or zero.")

In this example, we use the input() function to get a number from the user, convert it to an integer using int(), and store it in the number variable. The if-else statement then checks whether the number is greater than zero. If it is, it prints “The number is positive.” Otherwise, it prints “The number is negative or zero.”

You can also use multiple if-else statements together to handle more complex conditions. Here’s an example that checks whether a number is positive, negative, or zero:

number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")
elif number < 0:
    print("The number is negative.")
else:
    print("The number is zero.")

In this case, the elif statement allows us to check an additional condition. If the first condition is False, it moves to the elif statement and checks whether the number is less than zero. If that condition is True, it prints “The number is negative.” Finally, if both the first and second conditions are False, it executes the code block under the else statement and prints “The number is zero.”

Python conditional statement features:

  1. `if` statement: The `if` statement is the fundamental building block of a conditional statement. It allows you to execute a block of code if a certain condition is true. The syntax of the `if` statement is as follows:
if condition:
        # Code block to execute if the condition is True
  1. `else` statement: The `else` statement is used in conjunction with the `if` statement. It provides an alternative block of code to execute when the condition in the `if` statement is false. The syntax is as follows:
if condition:
       # Code block to execute if the condition is True
   else:
       # Code block to execute if the condition is False
  1. `elif` statement: The `elif` statement allows you to check additional conditions after an initial `if` statement. It provides a way to handle multiple cases within the same conditional statement. The syntax is as follows:
if condition1:
       # Code block to execute if condition1 is True
   elif condition2:
       # Code block to execute if condition1 is False and condition2 is True
   else:
       # Code block to execute if all conditions are False
  1. Nested conditional statements: Python allows you to nest if-else statements within other if-else statements. This means that you can have if-else statements inside the code blocks of other if-else statements. This feature enables handling more complex conditions and creating decision trees.
  2. Logical operators: Python provides logical operators such as `and`, `or`, and `not` that allow you to combine multiple conditions. These operators can be used within the condition of an if statement to create more complex conditions.
  3. Ternary operator: Python supports a ternary operator, which provides a concise way to write conditional expressions in a single line. The syntax is as follows:
value_if_true if condition else value_if_false

This operator allows you to assign a value based on a condition without writing a full if-else statement.

Python conditional statements advantages:

  1. Decision-making: Conditional statements provide a way to make decisions in your Python programs. They allow you to execute different blocks of code based on the evaluation of specific conditions. This enables your program to respond dynamically to different situations and perform different actions as needed.
  2. Flexibility: Conditional statements provide flexibility in controlling the flow of your program. By using conditions, you can define different paths or branches of execution based on varying inputs or states. This flexibility allows you to handle diverse scenarios and customize the behavior of your program accordingly.
  3. Code organization: Using conditional statements helps in organizing your code. By dividing your code into blocks based on conditions, you can make it more structured and readable. Each block of code within a conditional statement represents a specific case or behavior, making it easier to understand the logic and purpose of different parts of your program.
  4. Error handling: Conditional statements are often used for error handling and exception handling in Python. By checking certain conditions, you can identify and handle specific error scenarios or exceptional cases appropriately. This allows you to anticipate and respond to errors or unexpected inputs, improving the overall robustness of your program.
  5. Code efficiency: Conditional statements can help optimize your code by selectively executing relevant blocks of code based on conditions. This can reduce unnecessary computations or operations, improving the efficiency and performance of your program. For example, you can include conditional checks to avoid executing resource-intensive code when certain conditions are not met.
  6. Complex decision trees: With the ability to nest conditional statements and combine logical operators, you can create complex decision trees in Python. This allows you to handle intricate conditions and multiple cases effectively. By structuring your code in this manner, you can handle a wide range of possibilities and make your programs more adaptable to diverse scenarios.

Python conditional statement disadvantages:

  1. Code complexity: As the number of conditions and branches increases, conditional statements can make the code more complex and harder to understand. Nested if-else statements or multiple elif conditions can make the code difficult to follow and maintain, leading to potential bugs or errors.
  2. Code duplication: In certain cases, conditional statements can result in code duplication. If similar blocks of code need to be executed in different branches of the conditional statements, you may end up duplicating that code, which can lead to maintenance issues. Code duplication can make it harder to update or modify the logic consistently across multiple branches.
  3. Readability and maintainability: While conditional statements can provide flexibility, excessive or poorly organized conditional logic can decrease code readability and maintainability. If the conditional statements become too complex or nested, it may become challenging for other developers (including yourself in the future) to understand the code and make modifications.
  4. Potential for errors: The use of conditional statements introduces the possibility of logical errors, such as incorrect conditions or unintended behavior due to missing conditions. It’s important to carefully design and test the conditions to ensure they cover all relevant cases and produce the expected results.
  5. Scalability: Conditional statements may become less scalable when handling a large number of conditions or cases. If the number of conditions grows significantly, maintaining and extending the conditional logic can become cumbersome. In such cases, alternative approaches, such as using dictionaries or lookup tables, may be more appropriate to handle complex mappings or decision-making.
  6. Code coupling: Conditional statements can introduce tight coupling between different parts of your code, especially if the conditions rely on specific variables or states. This can make it harder to modify or refactor your code in the future without affecting other parts of the program.

Python conditional statement – If statement:

In Python, the if statement allows you to execute a block of code only if a certain condition is true. It provides a way to make decisions and control the flow of your program.The basic syntax of an if statement in Python is as follows:

age = 20

if age >= 18:
    print("You are an adult.")

The `condition` is an expression that evaluates to either `True` or `False`. If the condition is `True`, the code block immediately following the `if` statement will be executed. Otherwise, if the condition is `False`, the code block will be skipped, and the program will continue with the next line of code. Here’s an example:

temperature = 30

if temperature > 25:
    print("It's a hot day!")
print("Enjoy your day.")

In this example, we use the `input()` function to get a number from the user, convert it to an integer using `int()`, and store it in the `number` variable. The if statement then checks whether the number is greater than zero. If it is, it executes the code block under the if statement and prints “The number is positive.”

Python conditional statement – If-else statement:

In Python, the if-else statement allows you to execute different blocks of code based on certain conditions. It provides a way to make decisions and control the flow of your program. The basic syntax of an if-else statement in Python is as follows:

if condition:
    # code to execute if condition is true
else:
    # code to execute if condition is false

The `condition` is an expression that evaluates to either `True` or `False`. If the condition is `True`, the code block immediately following the `if` statement will be executed. Otherwise, if the condition is `False`, the code block following the `else` statement will be executed. Here’s an example:

score = 75

if score >= 60:
    print("Congratulations, you passed!")
else:
    print("Sorry, you failed.")

In this example, we use the `input()` function to get a number from the user, convert it to an integer using `int()`, and store it in the `number` variable. The if-else statement then checks whether the number is greater than zero. If it is, it executes the code block under the `if` statement and prints “The number is positive.” Otherwise, if the number is not greater than zero, it executes the code block under the `else` statement and prints “The number is negative or zero.”

Python conditional statement – elif statement:

In Python, the `elif` statement allows you to check additional conditions after an initial `if` statement. It provides a way to handle multiple cases and execute different blocks of code based on the conditions. The basic syntax of an `elif` statement in Python is as follows:

if condition1:
    # code to execute if condition1 is true
elif condition2:
    # code to execute if condition2 is true
else:
    # code to execute if neither condition1 nor condition2 is true

You can have as many `elif` statements as needed to handle different conditions. The conditions are evaluated one by one, from top to bottom. If a condition is `True`, the corresponding code block will be executed, and the remaining conditions will be skipped. If none of the conditions are `True`, the code block under the `else` statement will be executed. Here’s an example:

temperature = 45

if temperature > 85:
    print("It's really hot outside.")
elif temperature > 70:
    print("It's warm outside.")
elif temperature > 55:
    print("It's cool outside.")
elif temperature > 32:
    print("It's cold outside.")
else:
    print("It's freezing outside!")

In this example, we use the `input()` function to get the student’s score, convert it to an integer using `int()`, and store it in the `score` variable. The `elif` statements check the score against different ranges to determine the letter grade. If the score is greater than or equal to 90, it assigns the grade ‘A’. If the score is between 80 and 89, it assigns ‘B’, and so on. If none of the conditions are met, it assigns ‘F’ as the grade. Finally, we print the grade using the `print()` function.

Python nested conditional statement – nested if-else statements:

In Python, nested if-else statements allow you to have if-else statements within other if-else statements. They provide a way to handle complex conditions and execute different blocks of code based on multiple conditions. The basic syntax of a nested if-else statement in Python is as follows:

if condition1:
    # code to execute if condition1 is true
    if condition2:
        # code to execute if condition1 and condition2 true
    else:
        # code execute if condition1 true but condition2 false
else:
    # code to execute if condition1 is false

In a nested if-else statement, the inner if-else statement is indented further to the right than the outer if-else statement. The inner if-else statement is evaluated only if the condition of the outer if statement is `True`. Here’s an example:

age = 25
has_membership = True

if age >= 18:
    if has_membership:
        print("Welcome to the exclusive club!")
    else:
        print("Membership required for entry.")
else:
    print("You must be 18 or older to enter.")

In this example, we use the `input()` function to get the student’s score and whether they earned extra credit. The `elif` statements check the score against different ranges to determine the letter grade. However, the grade also depends on whether the student earned extra credit.

If the score is greater than or equal to 90, it checks the `credit` variable. If it is ‘yes’, it assigns the grade ‘A+’. Otherwise, it assigns ‘A’.

Similarly, for scores between 80 and 89, it checks the `credit` variable to assign either ‘B+’ or ‘B’.

If none of the conditions are met, it assigns ‘F’ as the grade.

Finally, we print the grade using the `print()` function.

Python If else Practice Programs

Python String Programs, Exercises, Examples

Python string is a sequence of characters, such as “hello”. They can be used to represent text in a programming language. Strings can be created by enclosing a sequence of characters between double quotes, such as “hello”, or by using the str() function.

1). Write a Python program to get a string made of the first and the last 2 chars from a given string. If the string length is less than 2, return instead of the empty string

2). Python string program that takes a list of strings and returns the length of the longest string.

3). Python string program to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).

4). Python string program to reverse a string if it’s length is a multiple of 4.

5). Python string program to count occurrences of a substring in a string.

6). Python string program to test whether a passed letter is a vowel or consonant.

7). Find the longest and smallest word in the input string.

8). Print most simultaneously repeated characters in the input string.

9). Write a Python program to calculate the length of a string with loop logic.

10). Write a Python program to replace the second occurrence of any char with the special character $.
Input = “Programming”
Output = “Prog$am$in$”

11). Write a python program to get to swap the last character of a given string.
Input = “SqaTool”
Output = “IqaTooS”

12). Write a python program to exchange the first and last character of each word from the given string.
Input = “Its Online Learning”
Output = “stI enlino gearninL”

13). Write a python to count vowels from each word in the given string show as dictionary output.
Input = “We are Learning Python Codding”
output = {“We” : 1, “are” : 2, “Learning” : 3, “Python”:1, “Codding”}

14). Write a python to repeat vowels 3 times and consonants 2 times.
Input = “Sqa Tools Learning”
Ouput = “SSqqaaa TToooooollss LLeeeaaarrnniiinngg”

15). Write a python program to re-arrange the string.
Input = “Cricket Plays Virat”
Output = “Virat Plays Cricket”

16). Write a python program to get all the digits from the given string.
Input = “””
Sinak’s 1112 aim is to 1773 create a new generation of people who
understand 444 that an organization’s 5324 success or failure is
based on 555 leadership excellence and not managerial
acumen
“””
Output = [1112, 5324, 1773, 5324, 555]

17). Write a python program to replace the words “Java” with “Python” in the given string.
Input = “JAVA is the Best Programming Language in the Market”
Output = “Python is the Best Programming Language in the Market”

18). Write a Python program to get all the palindrome words from the string.
Input = “Python efe language aakaa hellolleh”
output = [“efe”, “aakaa”, “hellolleh”]

19). Write a Python program to create a string with a given list of words.
Input = [“There”, “are”, “Many”, “Programming”, “Language”]
Output = There are many programming languages.

20). Write a Python program to remove duplicate words from the string.
Input = “John jany sabi row john sabi”
output = “John jany sabi row”

21). Write a Python to remove unwanted characters from the given string.
Input = “Prog^ra*m#ming”
Output = “Programming”

Input = “Py(th)#@&on Pro$*#gram”
Output = “PythonProgram”

22). Write a Python program to find the longest capital letter word from the string.
Input = “Learning PYTHON programming is FUN”
Output = “PYTHON”

23). Write a Python program to get common words from strings.
Input String1 = “Very Good Morning, How are You”
Input String1 = “You are a Good student, keep it up”
Output = “You Good are”

24). Write a Python program to find the smallest and largest word in a given string.
Input = “Learning is a part of life and we strive”
Output = “a”, “Learning”

25). Check whether the given string is a palindrome (similar) or not.
Input= sqatoolssqatools
Output= Given string is not a palindrome

26). Write a program using python to reverse the words in a string.
Input= sqatools python
Output= slootaqs

27). Write a program to calculate the length of a string.
Input= “python”
Output = 6

28). Write a program to calculate the frequency of each character in a string.
Input = “sqatools”
Output = {‘s’:2, ‘q’:1, ‘a’: 1, ‘t’:1,‘o’:2, ‘l’:1, ‘s’:1}

29). Write a program to combine two strings into one.
Input: 
A = ’abc’
B = ’def’
Output = abcdef

30). Write a program to print characters at even places in a string.
Input = ‘sqatools’
Output = saol

31). Write a program to check if a string has a number or not.
Input = ‘python1’
Output = ‘Given string have a number’

32). Write a python program to count the number of vowels in a string.
Input= ‘I am learning python’
Output= 6

33). Write a python program to count the number of consonants in a string.
Input= ‘sqltools’
Output= 6

34). Write a program to print characters at odd places in a string.
Input = ‘abcdefg’
Output = ‘bdf’

35). Write a program to remove all duplicate characters from a given string in python.
Input = ‘sqatools’
Output = ‘sqatol’

36). Write a program to check if a string has a special character or not
Input = ‘python$$#sqatools’
Output =  ‘Given string has special characters

37). Write a program to exchange the first and last letters of the string
Input = We are learning python
Output = ne are learning pythoW

38). Write a program to convert all the characters in a string to Upper Case.
Input = ‘I live in pune’
Output = ‘I LIVE IN PUNE’

39). Write a program to remove a new line from a string using python.
Input = ‘objectorientedprogramming\n’
Output = ‘Objectorientedprogramming’

40). Write a python program to split and join a string
Input =‘Hello world’
Output = [‘Hello’, ‘world’]
                 Hello-world

41). Write a program to print floating numbers up to 3 decimal places and convert it to string.
Input = 2.14652
Output= 2.146

42). Write a program to convert numeric words to numbers.
Input = ‘five four three two one’
Output = 54321

43). Write a python program to find the location of a word in a string
Input Word = ‘problems’
Input string = ‘ I am solving problems based on strings’
Output = 4

44). Write a program to count occurrences of a word in a string.

Word = ‘food’
Input str = ‘ I want to eat fast food’
Occurrences output= 1

Word = ‘are’
Input str = “We are learning Python, wow are you”
Occurrences output = 2 

45). Write a python program to find the least frequent character in a string.
Input =  ‘abcdabdggfhf’
Output = ‘c’

46). Find the words greater than the given length.
Ex length = 3
Input = ‘We are learning python’
Output – ‘learning python’

47). Write a program to get the first 4 characters of a string.
Input = ‘Sqatools’
Output = ‘sqat’

48). Write a Python program to get a string made of the first 2 and the last 2 chars from a given string.
Input = ‘Sqatools’
Output = ‘Sqls’ 

49). Write a python program to print the mirror image of the string.
Input = ‘Python’
Output = ‘nohtyp 

50). Write a python program to split strings on vowels
Input = ‘qwerty’
Output = ‘qw rty’

51). Write a python program to replace multiple words with certain words.
Input = “I’m learning python at Sqatools”
Replace python with SQA  and sqatools with TOOLS 
Output = “I’m learning SQA at TOOLS “

52). Write a python program to replace different characters in the string at once.
Input = ‘Sqatool python’
Replace a with 1,
Replace t with 2,
Replace o with 3
Output = ‘sq1233l py2h3n”

53). Write a python program to remove empty spaces from a list of strings.
Input = [‘Python’, ‘ ‘, ‘ ‘, ‘sqatools’]
Output = [‘Python’, ‘sqatools’] 

54).  Write a python program to remove punctuations from a string
Input = ‘Sqatools : is best, for python’
Output = ‘Sqatools is best for python’

55).  Write a python program to find duplicate characters in a string
Input = “hello world”
Output = ‘lo’

56).  Write a python program to check whether the string is a subset of another string or not
Input str1 = “iamlearningpythonatsqatools”
str = ‘pystlmi’
Output = True

57). Write a python program to sort a string
Input = ‘xyabkmp’
Output = ‘abkmpxy’

58). Write a python program to generate a random binary string of a given length.
Input = 8
Output = 10001001

59). Write a python program to check if the substring is present in the string or not
Input string= ‘I live in Pune’
Substring= ‘I live ‘
Output = ‘Yes

60). Write a program to find all substring frequencies in a string.
Input str1 = “abab” 
Output = {‘a’: 2, ‘ab’: 2, ‘aba’: 1,‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}  

61). Write a python program to print the index of the character in a string.
Input = ‘Sqatools’
Output = ‘The index of q is 1’

62). Write a program to strip spaces from a string.
Input = ‘    sqaltoolspythonfun     ‘ 
Output = ‘ sqaltoolspythonfun’

63). Write a program to check whether a string contains all letters of the alphabet or not.
Input = ‘abcdgjksoug’
Output = False

64). Write a python program to convert a string into a list of words.
Input = ‘learning python is fun’
Output = [learning, python, is, fun] 

65). Write a python program to swap commas and dots in a string.
Input = sqa,tools.python
Output = sqa.tools,python

66). Write a python program to count and display the vowels in a string
Input = ‘welcome to Sqatools’
Output = 7

67). Write a Python program to split a string on the last occurrence of the delimiter. 
Input = ‘l,e,a,r,n,I,n,g,p,y,t,h,o,n’
Output = [‘l,e,a,r,n,I,n,g,p,y,t,h,o ‘ ,’n’]

68). Write a Python program to find the first repeated word in a given string. 
Input = ‘ab bc ca ab bd’
Output = ‘ab’

69). Write a program to find the second most repeated word in a given string using python.
Input = ‘ab bc ac ab bd ac nk hj ac’
Output = (‘ab’, 2)

70). Write a Python program to remove spaces from a given string.
Input = ‘python at sqatools’
Output = ‘pythonatsqatools’

71). Write a Python program to capitalize the first and last letters of each word of a given string.
Input = ‘this is my first program’
Output = ‘ThiS IS MY FirsT PrograM’

72). Write a Python program to calculate the sum of digits of a given string.
Input = ’12sqatools78′
Output = 18

73). Write a Python program to remove zeros from an IP address. 
Input = 289.03.02.054
Output = 289.3.2.54

74). Write a program to find the maximum length of consecutive 0’s in a given binary string using python.
Input = 10001100000111
Output = 5 

75). Write a program to remove all consecutive duplicates of a given string using python.
Input = ‘xxxxyy’
Output = ‘xy’

76). Write a program to create strings from a given string. Create a string that consists of multi-time occurring characters in the said string using python.
Input = “aabbcceffgh”
Output = ‘abcf’

77). Write a Python program to create a string from two given strings combining uncommon characters of the said strings.  

Input string :
s1 = ‘abcdefg’
s2 = ‘xyzabcd’
Output string : ‘efgxyz’

78). Write a Python code to remove all characters except the given character in a string. 
Input = “Sqatools python”
Remove all characters except S
Output = ‘S’

79). Write a program to count all the Uppercase, Lowercase, special character and numeric values in a given string using python.
Input = ‘@SqaTools.lin’
Output:
Special characters: 1
Uppercase characters: 2
Lowercase characters: 8

80). Write a Python program to count a number of non-empty substrings of a given string.
Input a string = ‘sqatools12’
Number of substrings = 55

81). Write a program to remove unwanted characters from a given string using python.
Input = ‘sqa****too^^{ls’
Output = ‘Sqatools’

82). Write a program to find the string similarity between two given strings using python.
Input
Str1 = ‘Learning is fun in Sqatools’
Str2 = ‘Sqatools Online Learning Platform’

Output :
Similarity : 0.4

83). Write a program to extract numbers from a given string using python.
Input = ‘python 456 self learning 89’
Output = [456, 89]

84). Write a program to split a given multiline string into a list of lines using python.
Input =”’This string Contains
Multiple
Lines”’
Output = [‘This string Contains’, ‘Multiple’, ‘Lines’]

85). Write a program to add two strings as they are numbers using python.
Input :
a=’3′, b=’7′
Output  = ’10’

86). Write a program to extract name from a given email address using python.
Input = ‘student1@gmail.com’
Output = ‘student’

87). Write a  program that counts the number of leap years within the range of years using python. The range of years should be accepted as a string. 

(“1981-2001)  =  Total leap year 5

88). Write a program to insert space before every capital letter appears in a given word using python. 
Input = ‘SqaTools pyThon’
Output = ‘ Sqa Tools py Thon’ 

89). Write a program to uppercase half string using python.
Input = ‘banana’
Output = ‘banANA’

90). Write a program to split and join a string using “-“.
Input = ‘Sqatools is best’
Output = ‘Sqatools-is-best’

91). Write a python program to find permutations of a given string using in built function.
Input  = ‘CDE’
Output = [‘CDE’, ‘CED’ ‘EDC’, ‘ECD’, ‘DCE’, ‘DEC’]

92). Write a program to avoid spaces in string and get the total length
Input = ‘sqatools is best for learning python’
Output = 31

93). Write a program to accept a string that contains only vowels
Input = ‘python’
Output- ‘not accepted’

Input = ‘aaieou’
Output = ‘accepted’

94). Write a program to remove the kth element from the string
K=2
Input = ‘sqatools’
Output = ‘sqtools’

95). Write a program to check if a given string is binary or not.
Hint: Binary numbers only contain 0 or 1.

Input = ‘01011100’
Output = yes

Input = ‘sqatools 100’
Output = ‘No’

96). Write a program to add ‘ing’ at the end of the string using python.
Input = ‘xyz’
Output = ‘xyzing’

97). Write a program to add ly at the end of the string if the given string ends with ing.
Input = ‘winning’
Output = ‘winningly’

98). Write a program to reverse words in a string using python.
Input = ‘string problems’
Output = ‘problems string’

99). Write a program to print the index of each character in a string.
Input =  ‘sqatools’
Output :
Index of s is 0
Index of q is 1
Index of a is 2
Index of t is 3
Index of o is 4
Index of o is 5
Index of l is 6
Index of s is 7

100). Write a program to find the first repeated character in a string and its index.
Input = ‘sqatools’
Output = (s,0)

101). Write a program to swap cases of a given string using python.
Input = ‘Learning Python’
Output = ‘lEARNING pYTHON’

102). Write a program to remove repeated characters in a string and replace it with a single letter using python.
Input = ‘aabbccdd’
Output = ‘cabd’

103). Write a program to print a string 3 times using python.
Input = ‘sqatools’
Output = ‘sqatoolssqatoolssqatools’

104). Write a program to print each character on a new line using python.
Input = ‘python’
Output:
p
y
t
h
o
n

105). Write a program to get all the email id’s from given string using python.
Input str = “”” We have some employee whos john@gmail.com email id’s are randomly distributed jay@lic.com we want to get hari@facebook.com all the email mery@hotmail.com id’s from this given string.”””
Output = [‘john@gmail.com’, ‘ jay@lic.com’, ‘hari@facebook.com’, ‘mery@hotmail.com’ ]

106). Write a program to get a list of all the mobile numbers from the given string using python.
Input str = “”” We have 2233 some employee 8988858683 whos 3455 mobile numbers are randomly distributed 2312245566 we want 453452 to get 4532892234 all the mobile numbers 9999234355  from this given string.”””
Output = [‘8988858683’, ‘2312245566’, ‘4532892234’, ‘9999234355’]

Python Pandas Programs, Exercises

Python Pandas Programs helps to filter and sort the tabular data and gain expertise on it, Pandas is an open-source library for data analysis in Python. Pandas is one of the most popular and fastest-growing libraries in the Python ecosystem.

1). Python Pandas program to create and display a one-dimensional array-like object containing an array of data.
Output:
15
43
88
23

2). Python Pandas program to convert a series to a list and print its type.

3). Python Pandas program to add two series.
Input:
A=[1,6,9,5]
B=[5,2,4,5]
Output:
[6,8,13,10]

4). Python Pandas program to subtract two series.
Input:
A=[1,6,9,5]
B=[5,2,4,5]
Output:
[-4,4,5,0]

5). Python Pandas program to multiply two series.
Input:
A=[1,6,9,5]
B=[5,2,4,5]
Output:
[5,12,36,25]

6). Python Pandas program to divide two series.
Input:
A=[1,6,9,5]
B=[5,2,4,5]
Output:
[0.2,3,2.5,1]

7). Python Pandas program to check whether elements in the series are equal or not.
Input:
A=[1,6,9,5]
B=[5,2,4,5]
Output:
False
False
False
True

8). Python Pandas program to check whether elements in the series are greater than other series.
Input:
A=[1,6,9,5]
B=[5,2,4,5]
Output:
False
True
True
False

9). Python Pandas program to convert a dictionary to a series.
Input:
A={name: Virat, sport: cricket, age: 32}
Output:
Name Virat
Sport Cricket
Age 32

10). Python Pandas program to convert a NumPy array to a Pandas series.
Input:
[5,3,8,9,0]
Output:
0 5
1 3
2 8
3 9
4 0

11). Python Pandas program to change the data type of given a column or a Series.
Input:
0 54
1 27.90
2 sqa
3 33.33
4 tools
dtype: object
Output:
0 54.00
1 27.90
2 NaN
3 33.33
4 NaN
dtype:float64

12). Python Pandas program to convert a given Series to an array.
Input:
0 54
1 27.90
2 sqa
3 33.33
4 tools
dtype: object
Output:
[’54’, ‘27.90’,’sqa’,’33.33′, ‘tools’]

13). Python Pandas program to convert a series of lists into one series.
Input:
[Sqa, tool]
[Learning, python]
[Is, fun]
Output:
0 [Sqa, tool]
1 [Learning, python]
2 [Is, fun]
dtype: object

14). Python Pandas program to sort a given Series.
Input:
0 55
1 23
2 10
3 87
Output:
0 10
1 23
2 55
3 87

15). Python Pandas program to add some data to an existing series.
Input:
0 54
1 27.90
2 sqa
3 33.33
4 tools
Output:
0 54
1 27.90
2 sqa
3 33.33
4 tools
5 python
6 100

16). Python Pandas program to create a subset of a given series based on value and condition.
Input:
0 10
1 25
2 69
3 74
4 33
5 54
6 21
Output:
Subset of the above Data Series:
0 10
1 25
4 33
6 21

17). Python Pandas program to change the order of the index of a given series.
Input:
0 Sqa
1 tools
2 Learning
3 python
4 Is
5 fun
Output:
2 Learning
3 python
0 Sqa
1 tools
4 Is
5 fun

18). Python Pandas program to find the mean of the data of a given series.
Input:
0 5
1 4
2 8
3 6
Output:
5.75

19). Python Pandas program to find the standard deviation of the  given Series.
Input:
0 2
1 4
2 6
3 8
4 10
Output: = 3.162277

20). Python Pandas program to get the items of a series not present in another series.
Input:
A=
0 4
1 7
2 3
B=
0 9
1 4
2 3
Output:
Items of A that are not present in B
1 7

21). Python Pandas program to calculate the maximum value from a series.
Input:
0 54
1 38
2 67
3 87
Output:
87

22). Python Pandas program to calculate the minimum value from a series.
Input:
0 54
1 38
2 67
3 87
Output:
38

23). Python Pandas program to calculate the frequency of each value of a series.
Input:
0 3
1 0
2 3
3 2
4 2
5 0
6 3
7 3
8 2
Output:
0 2
2 3
3 4

24). Python Pandas program to extract items at given positions of a series.
Input:
0 3
1 0
2 3
3 2
4 2
5 0
6 3
7 3
8 2
Output:
1 0
4 2
7 3

25). Python Pandas program to convert the first and last character of each word to upper case in each word of a given series.
Input:
0 sqatools
1 python
2 data
3 science
Output:
0 SqatoolS
1 PythoN
2 DatA
3 SciencE

26). Python Pandas program to calculate the number of characters in each word in a series.
Input:
0 Virat
1 Rohit
2 Pant
3 Shikhar
Output:
0 6
1 6
2 4
3 7

27). Python Pandas program to convert a series of date strings to a time-series.
Input:
0 2 Feb 2020
1 5/11/2021
2 7-8-2022
Output:
0 2020-02-02 00:00:00
1 2021-11-05 00:00:00
2 2022-08-07 00:00:00

28). Python Pandas program to filter words from a given series that contain at least one vowel.
Input:
0 sqatools
1 SQL
2 python
3 white
4 bsc
Output:
0 sqatools
2 python
3 white

29). Python Pandas program to find the index of the first occurrence of the smallest and largest value of a series.
Input:
0 54
1 25
2 38
3 87
Output:
1
3

30). Python Pandas program to convert a dictionary into DataFrame.

31). Python Pandas program to print the first n rows of a Dataframe.

32). Python Pandas program to print the last n rows of a DataFrame.

33). Python pandas program to print the selected columns from DataFrame.
Input:
Sr.no. name age
1        Alex    30
2        John   27
3        Peter   29
Output:
name age
Alex     30
John    27
Peter   29

34). Python Pandas program to print the selected rows from DataFrame.
Input:
Sr.no. name age
1.        Alex   30
2.        John  27
3.        Peter 29
Output:
Sr.no. name age
2.       John   27

35). Python Pandas program to select the rows where the age is greater than 29.
Input:
Sr.no. name   age
1.       Alex.     30
2.       John.    27
3.       Peter.   29
4.       Klaus.   33
Output:
Sr.no. name age
1. Alex. 30
4. Klaus. 33

36). Python Pandas program to count the number of rows and columns in a DataFrame.
Input:
Sr.no. name   age
1.        Alex.   30
2.        John.   27
3.        Peter.  29
4.        Klaus.  33
Output:
No of rows:4
No of columns:3

37). Python Pandas program to select the rows where age is missing.
Input:
Sr.no. name  age
1.       Alex.   30
2.      John.   np.nan
3.      Peter.  29
4.      Klaus.  np.nan
Output:
Sr.no. name age
2.       John.  np.nan
4.       Klaus. np.nan

38). Python Pandas program to print the names who’s age is between 25-30 using Pandas.
Input:
Sr.no. name  age
1.       Alex.    30
2.       John.   27
3.       Peter.  29
4.       Klaus.  33
Output:
Sr.no. name  age
2.       John.   27
3.       Peter.  29

39). Python Pandas program to change the age of John to 24.
Input:
Sr.no. name  age
1.       Alex.    30
2.       John.   27
3.       Peter.  29
4.       Klaus.  33
Output:
Sr.no. name  age
1.       Alex.    30
2.       John.   24
3.       Peter.  29
4.       Klaus.  33

40). Python Pandas program to calculate the sum of age column.
Input:
Sr.no. name  age
1.       Alex.   30
2.      John.   27
3.      Peter.  29
4.      Klaus.  33
Output:
119

41). Python Pandas program to add a new row in the DataFrame.
Input:
Sr.no. name  age
1.       Alex.   30
2.      John.   27
3.      Peter.  29
4.      Klaus.  33
Output:
Sr.no. name  age
1.       Alex.    30
2.       John.   27
3.       Peter.  29
4.       Klaus.  33
5.      Jason.  28

42). Python Pandas program to sort the DataFrame first by ‘name’ in ascending order.
Input:
Sr.no. name  age
1.       Alex.    30
2.       John.   27
3.       Peter.  29
4.       Klaus.  33
Output:
Sr.no. name   age
1.       Alex.     30
2.       John.    27
4.       Klaus.   33
3.       Peter.   29

43). Python Pandas program to calculate the mean of age column.
Input:
Sr.no. name   age
1.       Alex.     30
2.       John.    27
3.       Peter.   29
4.       Klaus.   33
Output:
29.75

44). Python Pandas program to sort the DataFrame by ‘age’ column in ascending order.
Input:
Sr.no. name    age
1.       Alex.     30
2.       John.     27
3.       Peter.    29
4.       Klaus.    33
Output:
Sr.no. name    age
2.       John.     27
3.       Peter.    29
1.       Alex.      30
4.       Klaus.    33

45). Python Pandas program to replace John with Jim.
Input:
Sr.no. name  age
1.       Alex.    30
2.       John.   27
3.       Peter.  29
4.       Klaus.  33
Output:
Sr.no. name   age
1.       Alex.     30
2.       Jim.       27
3.       Peter.    29
4.       Klaus.    33

46). Python Pandas program to delete records for John.
Input:
Sr.no. name   age
1.       Alex.    30
2.       John.    27
3.       Peter.   29
4.       Klaus.   33
Output:
Sr.no. name age
1.       Alex.   30
3.       Peter.  29
4.       Klaus.  33

47). Python Pandas program to add a new column in a DataFrame.
Input:
Sr.no. name  age
1.       Alex.    30
2.       John.   27
3.       Peter.   29
4.       Klaus.   33
Output:
Sr.no. name   age. Salary
1.       Alex.     30.   50000
2.       John.    27.   65000
3.       Peter.   29.   58000
4.       Klaus.   33.   66000

48). Python Pandas program to iterate over rows in a DataFrame.
Input:
A=[{name:Yash, percentage:78},{name:Rakesh, percentage: 80},{
name: Suresh, percentage:60}]
Output:
Yash      78
Rakesh  80
Suresh   60

49). Python Pandas program to get a list of column headers from the DataFrame.
Input:
A={name:[Virat,Messi, Kobe], sport:[cricket, football, basketball]}
Output:
[name, sport]

50). Python Pandas program to rename columns of a given DataFrame.
Input:
C1. C2. C3
1. 6. 8
3. 8. 2
9. 0. 6
Output:
A. B. C
1. 6. 8
3. 8. 2
9. 0. 6

51). Python Pandas program to change the order of columns in a DataFrame.
Input:
Sr.no. name age. Salary
1.       Alex.   30.  50000
2.       John.  27.  65000
3.       Peter. 29.  58000
4.       Klaus. 33.  66000
Output:
Sr.no. name Salary   Age
1.       Alex.   50000.  30
2.       John.  65000   27
3.       Peter. 58000.   29
4.       Klaus. 66000   33

52). Python Pandas program to write a DataFrame to a CSV file using a tab separator.
Input:
Sr.no. name  age. Salary
1.       Alex.    30.   50000
2.       John.   27.   65000
3.       Peter.  29.   58000
4.       Klaus.  33.   66000
Output:
Sr.no\tname\tage\tSalary
1\tAlex\t30\t50000
2\tJohn\t27\t65000
3\tPeter\t29\t58000
4\tKlaus\t33\t66000

53). Python Pandas program to count Country wise population from a given data set (columns of a data set- Country, population).
Output:
Country. Population
China.     57289229
India.      49262728
.
.
.

54). Python Pandas program to replace all the NaN values with a scaler in a column of a Dataframe.
Input:
Sr.no. name  age
1.       Alex.    30
2.       John.   np.nan
3.       Peter.  29
4.       Klaus.  np.nan
Output:
Sr.no. name  age
1.       Alex.    30
2.       John.   25
3.       Peter.  29
4.       Klaus.  25

55). Python Pandas program to count the NaN values in a Dataframe.
Input:
Sr.no. name   age
1.       Alex.    30
2.       John.   np.nan
3.       Peter.   29
4.       Klaus.  np.nan
Output:
2

56). Python Pandas program to shuffle rows in a DataFrame.
Input:
Sr.no. name  age.   Salary
1.       Alex.    30.     50000
2.       John.    27.    65000
3.       Peter.   29.     63000
4.       Klaus.   33.    59000
Output:
Sr.no. name  age.  Salary
2.       John.   27.    65000
4.       Klaus.  33.    59000
1.       Alex.   30.     50000
3.       Peter.  29.     63000

57). Python Pandas program to rename a column in a DataFrame.
Input:
Rank. name  age.  Salary
1.       Alex.    30.    50000
2.       John.   27.    65000
3.       Peter.  29.    63000
4.       Klaus.  33.    59000
Output:
Sr.no. name age. Salary
1.       Alex.   30.   50000
2.       John.  27.   65000
3.       Peter. 29.   63000
4.       Klaus. 33.   59000

58). Python Pandas program to get a list of records in a  column of a DataFrame.
Input:
Sr.no. name age. Salary
1.       Alex.   30.   50000
2.       John.  27.   65000
3.       Peter. 29.   63000
4.       Klaus. 33.   59000
Output:
[Alex, John, Peter, Klaus]

59). Python Pandas program to find the row where the value of a column is maximum.
Input:
Sr.no. name age. Salary
1.       Alex.   30.   50000
2.       John.  27.   65000
3.       Peter. 29.   63000
4.       Klaus. 33.   59000
Output: Row where salary is maximum 2

60). Python Pandas program to find the row where the value of a given column is minimum.
Input:
Sr.no. name age. Salary
1.        Alex.   30.  50000
2.        John.  27.  65000
3.        Peter. 29.  63000
4.        Klaus. 33.  59000
Output= Row where salary is minimum 1

61). Python Pandas program to check whether a column is present in a DataFrame.
Input:
Sr.no. name  age. Salary
1.       Alex.   30.    50000
2.       John.   27.   65000
3.       Peter.  29.   63000
4.       Klaus. 33.    59000
Output:
The company column is not present in DataFrame
The name column is present in DataFrame

62). Python Pandas program to get the datatypes of columns of a DataFrame.
Input:
Sr.no. name   age.  Salary
1.        Alex.    30.    50000
2.        John.   27.    65000
3.        Peter.  29.     63000
4.        Klaus.  33.    59000
Output:
Sr.no. Int64
Name. Object
Age. Int64
Salary. Int64

63). Python Pandas program to convert a list of lists into a Dataframe. 
Input:
[[Virat, cricket],[Messi, football]]
Output:
0 column1 column2
1. Virat.      Cricket
2. Messi.    Football

64). Python Pandas program to find the index of a column from the DataFrame.
Input:
Sr.no. name   age. Salary
1.        Alex.    30.   50000
2.        John.   27.   65000
3.        Peter.  29.   63000
4.        Klaus.  33.   59000
Output: Index number of age is 2

65). Python Pandas program to select all columns except one column in a DataFrame.
Input:
Sr.no. name age.  Salary
1.       Alex.   30.    50000
2.       John.  27.    65000
3.       Peter.  29.   63000
4.       Klaus. 33.    59000
Output:
Sr.no. name   Salary
1.        Alex.   50000
2.        John.  65000
3.        Peter.  63000
4.        Klaus. 59000

66). Python Pandas program to remove the first n rows of a DataFrame. 
Input:
Sr.no. name  age. Salary
1.       Alex.   30.    50000
2.       John.   27.   65000
3.       Peter.  29.   63000
4.       Klaus.  33.   59000
Output:
After removing the first 2 rows
Sr.no. name age.  Salary
3.       Peter.  29.   63000
4.       Klaus.  33.   59000

67). Python Pandas program to remove the last n rows of a given DataFrame.
Input:
Sr.no. name  age. Salary
1.       Alex.   30.    50000
2.       John.  27.    65000
3.       Peter. 29.    63000
4.       Klaus. 33.    59000
Output:
After removing the last 2 rows
Sr.no. name age.  Salary
1.       Alex.   30.   50000
2.       John.  27.   65000

68). Python Pandas program to reverse the order of rows of a given DataFrame.
Input:
Sr.no. name   age. Salary
1.       Alex.     30.    50000
2.       John.    27.    65000
3.       Peter.   29.    63000
4.       Klaus.   33.    59000
Output:
Sr.no. name age. Salary
4.       Klaus. 33.   59000
3.       Peter. 29.   63000
2.       John.  27.   65000
1.       Alex.  30.   50000.

69). Python Pandas program to reverse the order of columns in a DataFrame.
Input:
Sr.no. name  age.  Salary
1.       Alex.    30.    50000
2.       John.    27.    65000
3.       Peter.   29.    63000
4.       Klaus.   33.    59000
Output:
Salary. age. Name. Sr.no.
50000. 30.    Alex.     1
65000. 27.   John.     2
63000. 29.   Peter.    3
59000. 33.   Klaus.    4

70). Python Pandas program to select columns by the object datatype from the DataFrame.
Input:
Sr.no. name  age. Salary
1.        Alex.  30.    50000
2.        John.  27.   65000
3.        Peter. 29.   63000
4.        Klaus. 33.   59000
Output:
Select string columns
Name
Alex
John
Peter
Klaus

71). Python Pandas program to convert continuous values of a column of a DataFrame to categorical.
Input:
{Student_id:[1,2,3,4], marks:[30,50,70,80]}
Output:
0. Marks
1. Fail
2. 2nd class
3. 1st class
4. 1st class with distinction

72). Python Pandas program to convert all the string values in the DataFrame to uppercases.
Input:
0. cricket
1. Yes
2. pass
3. FAIL
Output:
0. Cricket
1. Yes
2. Pass
3. Fail

73). Python Pandas program to check whether only the upper case is present in a column of a DataFrame.
Input:
0. Name
1. Kate
2. Jason
3. ROBERT
4. MARK
5. Dwyane
Output: 
0. Name.    Name
1. Kate.      False
2. Jason.     False
3. ROBERT True
4. MARK.   True
5. Dwyane. False

74). Python Pandas program to check whether only the lower case is present in a given column of a DataFrame .
Input:
0. Name
1. kate
2. jason
3. ROBERT
4. MARK
5. dwyane
Output:
0. Name.    Name
1. Kate.       True
2. Jason.     True
3. ROBERT  False
4. MARK.    False
5. dwyane. True

75). Python Pandas program to check whether only numeric values are present in a column of a DataFrame.

Input: 
0. Marks
1. Pass
2. 88
3. 2nd class
4. 90
5. Distinction
Output:
0. Marks.           Marks
1. Pass.              False
2. 88.                  True
3. 2nd class.      False
4. 90.                  True
5. Distinction.    False

76). Python Pandas program to check whether only alphabetic values present in a column of a DataFrame.
Input:
0. Marks
1. Pass
2. 88
3. First class
4. 90
5. Distinction
Output:
0. Marks.           Marks
1. Pass.              True
2. 88.                  False
3. First class.      False
4. 90.                  False
5. Distinction.    True

77). Python Pandas program to get the length of the integer of a column in a DataFrame.
Input:
0. Sales
1. 55000
2. 75000
3. 330000
4. 10000
Output:
0. Sales.        Sales_length
1. 55000.       5
2. 75000.       5
3. 330000.     6
4. 1000.         4

78). Python Pandas program to extract email from a specified column of a given DataFrame.
Input:
0. Company_mail
1. TCS. tcs@yahoo.com
2. Apple. apple@icloud.com
3 Google. google@gmail.com
Output:
0. Company_mail                         email
1. TCS. tcs@yahoo.com               tcs@yahoo.com
2. Apple. apple@icloud.com       apple@icloud.com
3 Google.google@gmail.com     google@gmail.com

79). Python Pandas program to extract the hash attached word from Twitter text from the specified column of a given DataFrame.
Input:
0. Tweets
1. Pune #love
2. #boycottmovie
3. enjoying #peace
Output:
0. Tweets                   extracted_word
1. Pune #love.           love
2. #boycottmovie.     boycottmovie
3. enjoying #peace   peace

80). Python Pandas program to extract only words from a column of a DataFrame.
Input:
Name      Address
Ramesh.   297 shukrawar peth
Suresh.     200 ravivar peth
Sanket.     090 shanivar peth
Output:
Name       Address                       Only_words
Ramesh.   297 shukrawar peth    shukrawar peth
Suresh.     200 ravivar peth          ravivar peth
Sanket.     090 shanivar peth        shanivar peth

81). Python Pandas program to join the two Dataframes along rows.
Input:
D1
Id Name. Age
1. Yash.     30
2. Gaurav.  27
3. Sanket.  28
D2
Id. Name.   Age
4. Atharva.  26
3. Tanmay.  22
Output:
Id Name.     Age
1. Yash.        30
2. Gaurav.    27
3. Sanket.    28
4. Atharva.  26
3. Tanmay.  22

82). Python Pandas program to join the two Dataframes along columns.
Input:
D1
Id Name.    Age
1. Yash.       30
2. Gaurav.   27
3. Sanket.   28
D2
Id.  Name.    Age
4.   Atharva.  26
3.   Tanmay.  22
Output:
Id  Name.    Age  Id.  Name.       Age
1.   Yash.      30.    4.   Atharva.    26
2.   Gaurav.  27.    3.  Tanmay.     22
3.   Sanket.   28

83). Python Pandas program to join the two Dataframes using the common column of both Dataframes.
Input:
D1
Id.  Name        marks1
S1. Ketan.       90
S2. Yash.         87
S3. Abhishek  77
D2
Id.  Name.    Marks2
S2. Yash.     70
S4. Gaurav. 65
Output:
Id.  Name. Marks1. name. Marks2
S2.  Yash.   87.         Yash.   70

84). Python Pandas program to merge two Dataframes with different columns.

85). Python Pandas program to detect missing values from a  DataFrame. 
Input:
Sr.no. name   age
1.       Alex.     30
2.       John.    np.nan
3.       Peter.    29
4.       Klaus.   np.nan
Output:
Sr.no. name   age
False   False.   False
False   False   True
False   False   False
False   False   True

86). Python Pandas program to identify the columns from the DataFrame which have at least one missing value.
Input:
Sr.no. name     age
1.       Alex.      30
2.       np.nan.  np.nan
3.       Peter.     29
4.       Klaus.     np.nan
Output:
Sr.no. False
Name. True
Age. True

87). Python Pandas program to count the number of missing values in each column of a DataFrame.
Input:
Sr.no. name     age
1.       Alex.       30
2.       np.nan.  np.nan
3.       Peter.     29
4.       Klaus.     np.nan
Output:
Sr.no. 0
Name. 1
Age. 2

88). Python Pandas program to drop the rows where at least one element is missing in a DataFrame.
Input:
Sr.no. name      age
1.        Alex.       30
2.        np.nan.   np.nan
3.        Peter.      29
4.        Klaus.     np.nan
Output:
Sr.no. name   age
1.        Alex.    30
3.        Peter.   29

89). Python Pandas program to drop the columns where at least one element is missing in a DataFrame.
Input:
Sr.no. name     age
1.        Alex.      30
2.        np.nan.  np.nan
3.        Peter.     29
4.        Klaus.     np.nan
Output:
Sr.no.
1
2
3
4

90). Python Pandas program to drop the rows where all elements are missing in a DataFrame.
Input:
Sr.no.           name    age
1.                 Alex.     30
np.nan        np.nan. np.nan
3.                 Peter.   29
4                 Klaus.   np.nan
Output:
Sr.no. name   age
1.        Alex.    30
3.        Peter.  29
4.        Klaus.  np.nan

91). Python Pandas program to replace NaNs with the value from the previous row in a DataFrame.
Input:
Sr.no. name     age
1.       Alex.      30
2.       np.nan.  np.nan
3.       Peter.     29
4.       Klaus.     22
Output:
Sr.no. name   age
1.       Alex.    30
2.       Alex.    30
3.       Peter.   29
4.       Klaus.   22

92). Python Pandas program to replace NaNs with the value from the next row in a DataFrame.
Input:
Sr.no. name     age
1.       Alex.       30
2.       np.nan.   np.nan
3.       Peter.      29
4.       Klaus.      22
Output:
Sr.no. name   age
1.       Alex.     30
2.       Peter.    29
3.       Peter.    29
4.       Klaus.    22

93). Python Pandas program to replace NaNs with mean in a DataFrame.
Input:
Sr.no. name     age
1.       Alex.       30
2.       np.nan.   np.nan
3.       Peter.     29
4.       Klaus.     22
Output:
Sr.no. name   age
1.       Alex.     30
2.       np.nan. 27
3.      Peter.    29
4.      Klaus.    22

94). Python Pandas program to replace the missing values with the most frequent values present in each column of a given DataFrame.
Input:
Sr.no. name    age
1.       Alex.      30
2.       np.nan.  np.nan
3.       Peter.     29
4.       Klaus.     22
5.       Stefen.    22
Output:
Sr.no. name    age
1.       Alex.      30
2.       np.nan.  22
3.       Peter.     29
4.       Klaus.     22
5.       Stefen.   22

95). Python Pandas program to replace NaNs with the median value in a DataFrame.
Input:
Sr.no. name    age
1.       Alex.     30
2.       np.nan. np.nan
3.       Peter.    29
4.       Klaus.    22
Output:
Sr.no. name  age
1.       Alex.    30
2.       John.   29
3.       Peter.  29
4.       Klaus.  22

96). Python Pandas program to import a CSV file.

97). Python Pandas program to import an xlsx file.

Python Tuple Practice Programs, Exercises

Python tuple practice programs help students to improve their logic building.

1). Python tuple program to create a tuple with 2 lists of data.
Input lists:
list1 = [4, 6, 8]
list2 = [7, 1, 4]
Output= ((4, 7), (6, 1), (8, 4))

2). Python tuple program to find the maximum value from a tuple.
Input = (41, 15, 69, 55)
Output = 69

3). Python tuple program to find the minimum value from a tuple.
Input = (36,5,79,25)
Output = 5

4). Python tuple program to create a list of tuples from a list having a number and its square in each tuple.
Input = [4,6,3,8]
Output = [ (4, 16), (6, 36), (3, 27), (8, 64) ]

5). Python tuple program to create a tuple with different datatypes.
Output= ( 2.6, 1, ‘Python’, True, [5, 6, 7], (5, 1, 4), {‘a’: 123, ‘b’: 456})

6). Python tuple program to create a tuple and find an element from it by its index no.
Input = (4, 8, 9, 1)
Index = 2
Output = 9

7). Python tuple program to assign values of tuples to several variables and print them.
Input = (6,7,3)
Variables = a,b,c
Output:
a, 6
b, 7
c, 3

8). Python tuple program to add an item to a tuple.
Input= ( 18, 65, 3, 45)
Output=(18, 65, 3, 45, 15)

9). Python tuple program to convert a tuple into a string.
Input = (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’, ‘s’)
Output = Sqatools

10). Python tuple program to get the 2nd element from the front and the 3rd element from the back of the tuple.
Input = (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’ ,’l’, ‘s’)
Output=
q
o

11). Python tuple program to check whether an element exists in a tuple or not.
Input = ( ‘p’ ,’y’, ‘t’, ‘h’, ‘o’, ‘n’)
P in A
Output=
True

12). Python tuple program to add a list in the tuple.
Input:
L=[12,67]
A=(6,8,4)
Output:
A=(6,8,4,12,67)

13). Python tuple program to find sum of elements in a tuple.
Input:
A=(4,6,2)
Output:
12

14). Python tuple program to add row-wise elements in Tuple Matrix
Input:
A = [[(‘sqa’, 4)], [(‘tools’, 8)]]
B = (3,6)
Output:
[[(‘sqa’, 4,3)], [(‘tools’, 8,6)]]

15). Python tuple program to create a tuple having squares of the elements from the list.
Input = [1, 9, 5,  7, 6]
Output = (1, 81, 25, 49, 36)

16). Python tuple program to multiply adjacent elements of a tuple.
Input = (1,2,3,4)
Output =  (2,6,12)

17). Python tuple program to join tuples if the initial elements of the sub-tuple are the same.
Input:
[(3,6,7),(7,8,4),(7,3),(3,0,5)]
Output:
[(3,6,7,0,5),(7,8,4,3)]

18). Python tuple program to convert a list into a tuple and multiply each element by 2.
Input = [12,65,34,77]
Output = (24, 130, 68, 154)

19). Python tuple program to remove an item from a tuple.
Input:
A=(p,y,t,h,o,n)
Output: (p,y,t,o,n)

20). Python tuple program to slice a tuple.
Input:
A=(5,7,3,4,9,0,2)
Output:
(5,7,3)
(3,4,9)

21). Python tuple program to find an index of an element in a tuple.
Input:
A=(s,q,a,t,o,o,l,s)
Index of a?
Output = 2

22). Python tuple program to find the length of a tuple.
Input:
A=(v,i,r,a,t)
Output=
5

23). Python tuple program to convert a tuple into a dictionary.
Input:
A=((5,s),(6,l))
Output = { s: 5, l: 6 }

24). Python tuple program to reverse a tuple.
Input = ( 4, 6, 8, 3, 1)
Output= (1, 3, 8, 6, 4)

25). Python tuple program to convert a list of tuples in a dictionary.
Input = [ (s, 2), (q, 1), (a, 1), (s, 3), (q, 2), (a, 4) ]
Output ={ s: [ 2, 3 ], q: [ 1, 2 ], a: [ 1 ,4 ] }

26). Python tuple program to pair all combinations of 2 tuples.
Input :
A=(2,6)
B=(3,4)
Output
[ (2, 3), (2, 4), (6, 3), (6, 4), (3, 2), (3, 6), (4, 2), (4, 6) ]

27). Python tuple program to remove tuples of length i.
Input = [ (2, 5, 7), (3, 4), ( 8, 9, 0, 5) ]
i=2
Output= [ (2, 5, 7), ( 8, 9, 0, 5) ]

28). Python tuple program to remove tuples from the List having an element as None.
Input = [(None, 2), (None, None), (5, 4), (1,6,7)]
Output= { (5, 4), (1, 6, 7) }

29). Python tuple program to remove Tuples from the List having every element as None.
Input = [(None,), (None, None), (5, 4), (1,6,7),(None,1)]
Output = [(5, 4), (1,6,7),(None,1)]

30). Python tuple program to sort a list of tuples by the first item.
Input = [ (1, 5), (7, 8), (4, 0), (3, 6) ]
Output = [ (1, 5), (3, 6), (4, 0), (7, 8) ]

31). Python tuple program to sort a list of tuples by the second item.
Input = [ (1, 5), (7, 8), (4, 0), (3, 6) ]
Output = [ (4, 0), (1, 5), (3, 6), (7, 8) ]

32). Python tuple program to sort a list of tuples by the length of the tuple.
Input = [(4, 5, 6), ( 6, ), ( 2, 3), (6, 7, 8, 9, 0 ) ]
Output=
[(6,),(2,3),(4,5,6),(6,7,8,9,0)]

33). Python tuple program to calculate the frequency of elements in a tuple.
Input=
(a, b, c, d, b, a, b)
Output=
{ a:2, b:3, c:1, d:1 }

34). Python tuple program to filter out tuples that have more than 3 elements.
Input=
[ (1, 4), (4, 5, 6), (2, ), (7, 6, 8, 9), (3, 5, 6, 0, 1) ]
Output= [(7, 6, 8, 9), (3, 5, 6, 0, 1)]

35). Python tuple program to assign the frequency of tuples to each tuple.
Input=
[ (s,q), (t, o, o, l), (p, y), (s, q) ]
Output= {(‘s’, ‘q’): 2, (‘t’, ‘o’, ‘o’, ‘l’): 1, (‘p’, ‘y’): 1}

36). Python program to find values of tuples at ith index number.
Input=
[ (1, 2, 3), (6, 5, 4), (7, 6, 8), (9, 0, 1) ]
I = 3
Output= (9,0,1)

37). Python tuple program to test whether a tuple is distinct or not.
Input=
(1,2,3,4)
(3,4,5,4,6,3)
Output=
Tuple is distinct
Tuple is not distinct

38). Python tuple program to convert a tuple to string datatype.
Input=
A=(4,1,7,5)
Output=
The given tuple is (4,1,7,5)

39). Python tuple program to remove empty tuples from a list of tuples.
Input=
[ (”,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’), () ]
Output=
[ (‘a’, ‘b’), (‘a’,  ‘b’,  ‘c’),  (‘d’) ]

40). Python tuple program to sort a tuple by its float element.
Input=
[(3,5.6),(6,2.3),(1,1.8)]
Output=
[(1,1.8),(6,2.3),(3,5.6)]

41). Python tuple program to count the elements in a list if an element is a tuple.
Input=
[1,6,8,5,(4,6,8,0),5,4)]
Output=
4

42). Python tuple program to multiply all the elements in a tuple.
Input=
(5,4,3,1)
Output=
60

43). Python tuple program to convert a string into a tuple.
Input=
“Sqatools”
Output=
(S,q,a,t,o,o,l,s)

44). Python tuple program to convert a tuple of string values to a tuple of integer values.
Input=
( ‘4563’, ’68’, ‘1,’ )
Output=
( 4563, 68, 1)

45). Python tuple program to convert a given tuple of integers into a number.
Input=
(4, 5, 3, 8)
Output=
4538

46). Python tuple program to compute the element-wise sum of tuples.
Input=
(1, 6, 7)
(4, 3, 0)
(2, 6, 8)
Output=
(7, 15, 15)

47). Python tuple program to convert a given list of tuples to a list of lists.
Input=
A=[(1,5),(7,8),(4,0)]
Output =
[ [1, 5], [7, 8], [4, 0] ]

48). Python tuple program to find all the tuples that are divisible by a number.
Input=
[(10,5,15),(25,6,35),(20,10)]
Output=
[(10,5,15),(20,10)]

49). Python tuple program to find tuples having negative elements.
Input=
[ (1, 7), (-4, -5), (0, 6), (-1, 3) ]
Output=
[(-4,-5),(-1,3)]

50). Python tuple program to find the tuples with positive elements.
Input=
[ (1, 7), (-4, -5), (0, 6), (-1, 3) ]
Output=
[ (1, 7), (0, 6) ]

51). Python tuple program to remove duplicates from a tuple.
Input=
(6, 4, 9, 0, 2, 6, 1, 3, 4)
Output=
(6, 4, 9, 0, 2, 1, 3)

52). Python tuple program to extract digits from a list of tuples.
Input=
[ (6, 87, 7), (4, 53), (11, 28, 3) ]
Output=
[ 1, 2, 3, 4, 5, 6, 7, 8 ]

53). Python tuple program to multiply ith element from each tuple from a list of tuples.
Input=
[ (4, 8, 3), (3, 4, 0), (1, 6, 2) ]
i=1
Output=
192

54). Python tuple program to flatten a list of lists into a tuple.
Input=
[ [s], [q], [a], [t], [o], [o], [l], [s] ]
Output=
(s, q, a, t, o, o, l, s)

55). Python tuple program to flatten a tuple list into a string.
Input=
[ (s, q, a), (t, o), (o, l, s) ]
Output=
‘s q a t o o l s’

56). Python tuple program to convert a tuple into a list by adding the string after every element of the tuple.
Input=
A=(1, 2, 3, 4), b=’sqatools’
Output=
[1, “sqatools”, 2, “sqatools”, 3, “sqatools”, 4, “sqatools”]

57). Write a program to convert a tuple to tuple pair.
Input=
(1, 2, 3)
Output=
[ (1, 2), (1, 3) ]

59). Python tuple program to convert a list of lists to a tuple of tuples.
Input=
[ [‘sqatools’], [‘is’], [‘best’]]
Output=
( (‘sqatools’), (‘is), (‘best’) )

60). Python tuple program to extract tuples that are symmetrical with others from a list of tuples.
Input=
[ (a, b, c), (d, e), (c, b, a) ]
Output=
(a, b, c)

61). Python tuple program to return an empty set if no tuples are symmetrical.
Input=
[(1, 5, 7), (3, 4), (4, 9, 0)]
Output=
set()

62). Python tuple program to remove nested elements from a tuple.
Input=
( ‘s’, ‘q’, ‘a’, (‘t’, ‘o’, ‘o’, ‘l’, ‘s’), ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’ )
Output=
(‘s’, ‘q’, ‘a’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’ ,’t’)

63). Python tuple program to sort a tuple by the maximum value of a tuple.
Input=
[ (1, 5, 7), (3, 4, 2), (4, 9, 0) ]
Output=
[ (4, 9, 0), (1, 5, 7), (3, 4, 2) ]

64). Python tuple program to sort a list of tuples by the minimum value of a tuple.
Input=
[(1,5,7),(3,4,2),(4,9,0)]
Output=
[(4,9,0),(1,5,7),(3,4,2)]

65). Python tuple program to concatenate two tuples.
Input=
(‘s’,’q’,’a)
(‘t’,’o’,’o,’l’)
Output=
((‘s’,’q’,’a),(‘t’,’o’,’o,’l’))

66). Python tuple program to order tuples by external list.
Input=
a=[(‘very’,8),(‘i’,6),(‘am,5),(‘happy’,0)]
List=[‘i’,’am’,’very’,’happy’]
Output=
[(‘i’,6),(‘am’,5),(‘very’,8),(‘happy’,0)]

67). Python tuple program to find common elements between two lists of tuples.
Input=
A=[(1,5),(4,8),(3,9)]
B=[(9,3),(5,6),(5,1),(0,4)]
Output=
{(3,9),(1,5)}

68). Python tuple program to convert a binary tuple to an integer.
Input=
A=(1,0,0)
Output=
4
Explanation=
2^2+0+0=4

69). Python tuple program to count the total number of unique tuples.
Input=
[ (8, 9), (4, 7), (3, 6), (8, 9) ]
Output=
3

70). Python tuple program to calculate the average of the elements in the tuple.
Input=
(5, 3, 9, 6)
Output=
5.75

71). Python tuple program to swap tuples.
Input=
A=(7,4,9)
B=(3,)
Output=
A=(3,)
B=(7,4,9)

72). Python tuple program to check the type of the input and return True if the type is a tuple and False if it is not a tuple.
Input=
A=( 7, 4, 9, 2, 0 )
Output=
True

73). Python tuple program to find the last element of a tuple using negative indexing.
Input=
A=(‘p’,y’,’t’,’o’,’n’)
Output=
n

Python If else Practice Programs, Exercises

Python If else practice programs help beginners to get expertise in conditional programming login. The if-else statement is a conditional statement in programming. It executes a set of instructions if a particular condition is true, and another set of instructions if the condition is false.

1). Python program to check given number is divided by 3 or not.

2). If else program to get all the numbers divided by 3 from 1 to 30.

3). If else program to assign grades as per total marks.
marks > 40: Fail
marks 40 – 50: grade C
marks 50 – 60: grade B
marks 60 – 70: grade A
marks 70 – 80: grade A+
marks 80 – 90: grade A++
marks 90 – 100: grade Excellent
marks > 100: Invalid marks

4). Python program to check the given number divided by 3 and 5.

5). Python program to print the square of the number if it is divided by 11.

6). Python program to check given number is a prime number or not.

7). Python program to check given number is odd or even.

8). Python program to check a given number is part of the Fibonacci series from 1 to 10.

9). Python program to check authentication with the given username and password.

10). Python program to validate user_id in the list of user_ids.

11). Python program to print a square or cube if the given number is divided by 2 or 3 respectively.

12). Python program to describe the interview process.

13). Python program to determine whether a given number is available in the list of numbers or not.

14). Python program to find the largest number among three numbers.

15). Python program to check any person eligible to vote or not
age > 18+ : eligible
age < 18: not eligible

16). Python program to check whether any given number is a palindrome.
Input: 121
Output: palindrome

17). Python program to check if any given string is palindrome or not.
Input: ‘jaj’
output = palindrome

18). Python program to check whether a student has passed the exam. If marks are greater than 35 students have passed the exam.
Input = Enter marks: 45
Output = Pass

19). Python program to check whether the given number is positive or not.
Input = 20
Output = True

20). Python program to check whether the given number is negative or not.
Input = -45
Output = True

21). Python program to check whether the given number is positive or negative and even or odd.
Input = 26
Output = The given number is positive and even

22). Python program to print the largest number from two numbers.
Input:
25, 63
Output = 63

23). Python program to check whether a given character is uppercase or not.
Input = A
Output = The given character is an Uppercase

24). Python program to check whether the given character is lowercase or not.
Input = c
Output = True

25). Python program to check whether the given number is an integer or not.
Input = 54
Output = True

26). Python program to check whether the given number is float or not.
Input = 12.6
Output = True

27). Python program to check whether the given input is a string or not.
Input = ‘sqatools’
Output = True

28). Python program to print all the numbers from 10-15 except 13
Output:
10
11
12
14

29). Python program to find the electricity bill. According to the following conditions:
Up to 50 units rs 0.50/unit
Up to 100 units rs 0.75/unit
Up to 250 units rs 1.25/unit
above 250 rs 1.50/unit
an additional surcharge of 17% is added to the bill
Input = 350
Output = 438.75

30). Python program to check whether a given year is a leap or not.
Input = 2000
Output = The given year is a leap year

31). Python Python program to check whether the input number if a multiple of two print “Fizz” instead of the number and for the multiples of three print “Buzz”. For numbers that are multiples of both two and three print “FizzBuzz”.
Input = 14
Output = Fizz
Input = 9
Output = Buzz
Input = 6
Output = FizzBuzz

32). Python program to check whether an alphabet is a vowel.
Input = A
Output = True

33). Python program to check whether an alphabet is a consonant.
Input = B
Output = True

34).  Python program to convert the month name to the number of days.
Input = February
Output = 28/29 days

35). Python program to check whether a triangle is equilateral or not. An equilateral triangle is a triangle in which all three sides are equal.
Input:
Enter the length of the sides of the triangle
A=10
B=10
C=10
Output = True

36). Python program to check whether a triangle is scalene or not. A scalene triangle is a triangle that has three unequal sides.
Input:
Enter the length of the sides of the triangle
A=10
B=15
C=18
Output = True

37). Python program to check whether a triangle is isosceles or not. An isosceles triangle is a triangle with (at least) two equal sides.
Input:
Enter the length of the sides of the triangle
A=10
B=15
C=10
Output = True

38). Python program that reads month and returns season for that month.
Input = February
Output = Summer

39). Python program to check whether the input number is a float or not if yes then round up the number to 2 decimal places.
Input = 25.3614
Output = 25.36

40). Python program to check whether the input number is divisible by 12 or not.
Input = 121
Output = True

41). Python program to check whether the input number is a square of 6 or not.
Input = 37
Output = False

42). Python program to check whether the input number is a cube of 3 or not.
Input = 27
Output = True

43). Python program to check whether two numbers are equal or not.
Input:
A=26,B=88
Output = The given numbers are not equal

44). Python program to check whether the given input is a complex type or not.
Input:
a=5+6j
Output: True

45). Python program to check whether the given input is Boolean type or not.
Input:
a=True
Output = The given variable is Boolean

46). Python program to check whether the given input is List or not.
Input:
a=[1,3,6,8]
Output = True

47). Python program to check whether the given input is a dictionary or not.
Input:
A={‘name’:’Virat’,’sport’:’cricket’}
Output = True

48). Python program to check the eligibility of a person to sit on a roller coaster ride or not. Eligible when age is greater than 12.
Input = 15
Output = You are eligible

49). Python program to create 10 groups of numbers between 1-100 and find out given input belongs to which group using python nested if else statements.
Input= 36
Output = The given number belongs to 4th group

50). Python program to find employees eligible for bonus. A company decided to give a bonus of 10% to employees. If the employee has served more than 4 years. Ask the user for years served and check whether an employee is eligible for a bonus or not.
Input = Enter Years served: 5
Output = You are eligible for a bonus

51). Take values of the length and breadth of a rectangle from the user and check if it is square or not using the python if else statement.
Input:
Length= 4
Breadth= 5
Output = It is not a square

52). A shop will give a 10% discount if the bill is more than 1000, and 20% if the bill is more than 2000. Using the python program Calculate the discount based on the bill.
Input = 1500
Output = Discount amount: 150

53). Python program to print the absolute value of a number defined by the user.
Input = -1
Output = 1

54). Python program to check the student’s eligibility to attend the exam based on his/her attendance. If attendance is greater than 75% eligible if less than 75% not eligible.
Input = Enter attendance: 78
Output = You are eligible

55). Python program to check whether the last digit of a number defined by the user is divisible by 4 or not.
Input = 58
Output = The last digit is divisible by 4

56). Python program to display 1/0 if the user gives Hello/Bye as output.
Input = Enter your choice: Hello
Output = 1
Input = Enter your choice: Bye
Output = 0

57). Python program to accept the car price of a car and display the road tax to be paid according to the following criteria:
Cost price<500000 –> tax:15000
Cost price<1000000 –> tax:50000
Cost price<1500000 –> tax:80000
Input = Car Price: 1200000
Output = Tax payable: 50000

58). Using a python program take input from the user between 1 to 7 and print the day according to the number. 1 for Sunday 2 for Monday so on.
Input = Enter number: 7
Output = Saturday

59). Python program to accept the city name and display its monuments (take Pune and Mumbai as cities).
Input = Enter city name: Pune
Output:
Shaniwar vada
Lal mahal
Sinhgad fort

60). Python program to check whether the citizen is a senior citizen or not. An age greater than 60 than the given citizen is a senior citizen.
Input = Enter age: 70
Output = The given citizen is a senior citizen

61). Python program to find the lowest number between three numbers.
Input:
A=45
B=23
C=68
Output = 23

62). Python program to accept the temperature in Fahrenheit and check whether the water is boiling or not.
Hint: The boiling temperature of water in Fahrenheit is 212 degrees
Input = Enter temperature: 190
Output = Water is not boiling

63). Python program to accept two numbers and mathematical operations from users and perform mathematical operations according to it.
Input:
A=30
B=45
Operation = +
Output = 75

64). Python program to accept marks from the user allot the stream based on the following criteria.
Marks>85: Science
Marks>70: Commerce
35<Marks<70: Arts
Marks<35: Fail
Input = Marks: 88
Output = Science

Python Basic Programs, Exercises

Python basic programs contains Python Programming Examples with all native Python data type, mathematical operations on Python Variables. Typecasting of Python Variables and get understanding of Python Fundamentals.

1). Python Program to add two integer values.

2). Python Program to subtract two integer values.

3). Python program to multiply two numbers.

4). Python program to repeat a given string 5 times.
Input :
str1 = “SQATools”
Output :
“SQAToolsSQAToolsSQAToolsSQAToolsSQATools” 

5). Python program to get the Average of given numbers.
Formula: sum of all the number/ total number
Input:
a = 40
b = 50
c = 30
Output :
Average = 40

6). Python program to get the median of given numbers.
Note: all the numbers should be arranged in ascending order
Formula : (n+1)/2
n = Number of values
Input : [45, 60, 61, 66, 70, 77, 80]
Output:  66

7). Python program to print the square and cube of a given number.
Input :
num1 = 9
Output :
Square = 81
Cube =   729

8). Python program to interchange values between variables.
Input :
a = 10
b = 20
Output :
a = 20
b = 10

9). Python program to solve this Pythagorous theorem.
Theorem : (a2 + b2 = c2)

10). Python program to solve the given math formula.
Formula : (a + b)2 = a^2 + b^2 + 2ab

11). Python program to solve the given math formula.
Formula : (a – b)2 = a^2 + b^2 – 2ab

12). Python program to solve the given math formula.
Formula : a2 – b2 = (a-b)(a+b)

13). Python program to solve the given math formula.
Formula : (a + b)3 = a3 + 3ab(a+b) + b3 

14). Python program to solve the given math formula.
Formula : (a – b)3 = a3 – 3a2b + 3ab2 – b3

15). Python program to calculate the area of the square.
Formula : area = a*a

16). Python program to calculate the area of a circle.
Formula = PI*r*r
r = radius
PI = 3.14

17). Python program to calculate the area of a cube.
Formula = 6*a*a

18). Python program to calculate the area of the cylinder.
Formula = 2*PI*r*h + 2*PI*r*r

19). Python program to check whether the given number is an Armstrong number or not.
Example: 153 = 1*1*1 + 5*5*5 + 3*3*3

20). Python program to calculate simple interest.
Formula = P+(P/r)*t
P = Principle Amount
r = Anual interest rate
t = time

21). Python program to print the current date in the given format
Output: 2023 Jan 05
Note: Use the DateTime library

22). Python program to calculate days between 2 dates.
Input date : (2023, 1, 5) (2023, 1, 22)
Output: 17 days

23). Python program to get the factorial of the given number.

24). Python program to reverse a given number.

25). Python program to get the Fibonacci series between 0 to 50.

26). Python program to check given number is palindrome or not.

27). Python program to calculate compound interest.

28). Python program to check the prime number.

29). Python program to check leap year.

30). Python program to check for the anagram.
Note: rearrangement of the letters of a word to another word, using all the original letters exactly once.

31). Python program to generate random numbers.

32). Python program to generate a random string with a specific length.

33). Python program to get the current date.

34). Python program to convert Decimal to Binary.

35). Python program to find the sum of natural numbers.

36). Python program to find HCF.

37). Python program to find LCM.

38). Python program to find the square root of a number.
Note: Use the math library to get the square root.

39). Python program to calculate the volume of a sphere.
Formula = (4/3*pi*r^2)
r = radius
pi = 3

40). Python program to perform mathematical operations on two numbers.

Python Functional, Programs And Excercises

A Python function is a sequence of statements that executes a specific task. A function can take arguments, which are the information passed to the function when it is called. Functions can also return values, which are the result of executing the function.

1). Python function program to add two numbers.

2). Python function program to print the input string 10 times.

3). Python function program to print a table of a given number.

4). Python function program to find the maximum of three numbers.

Input: 17, 21, -9
Output: 21

5). Python function program to find the sum of all the numbers in a list.
Input : [6,9,4,5,3]
Output: 27

6). Python function program to multiply all the numbers in a list.
Input : [-8, 6, 1, 9, 2]
Output: -864

7). Python function program to reverse a string.
Input: Python1234
Output: 4321nohtyp

8). Python function program to check whether a number is in a given range.
Input : num = 7, range = 2 to 20
Output: 7 is in the range

9). Python function program that takes a list and returns a new list with unique elements of the first list.
Input : [2, 2, 3, 1, 4, 4, 4, 4, 4, 6]
Output : [2, 3, 1, 4, 6 ]

10). Python function program that take a number as a parameter and checks whether the number is prime or not.
Input : 7
Output : True

11). Python function program to find the even numbers from a given list.
Input : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output : [2, 4, 6, 8]

12). Python function program to create and print a list where the values are squares of numbers between 1 to 10.
Input: 1 to 10
Output: 1, 4, 9, 16, 25, 36, 49, 64, 81

13). Python function program to execute a string containing Python code.

14). Python function program to access a function inside a function.

15). Python function program to find the LCM of two numbers.
Input: 12, 20
Output: 60

16). Python function program to calculate the sum of numbers from 0 to 10.
Output: 55

17). Python function program to find the HCF of two numbers.
Input: 24 , 54
Output: 6

18). Python function program to create a function with *args as parameters.
Input: 5, 6, 8, 7
Output: 125 216 512 343

19). Python function program to get the factorial of a given number.
Input: 5
Output: 120

20). Python function program to get the Fibonacci series up to the given number.
Input: 10
Output: 1 1 2 3 5 8 13 21 34

21). Python function program to check whether a combination of two numbers has a sum of 10 from the given list.
Input : [2, 5, 6, 4, 7, 3, 8, 9, 1]
Output : True

1, 22). Python function program to get unique values from the given list.
Input : [4, 6, 1, 7, 6, 1, 5]
Output : [4, 6, 1, 7, 5]

23). Python function program to get the duplicate characters from the string.
Input: Programming
Output: {‘g’,’m’,’r’}

24). Python function program to get the square of all values in the given dictionary.
Input = {‘a’: 4, ‘b’ :3, ‘c’ : 12, ‘d’: 6}
Output = {‘a’: 16, ‘b’ : 9, ‘c’: 144, ‘d’, 36}

25). Python function program to create dictionary output from the given string.
Note: Combination of the first and last character from each word should be
key and the same word will the value in the dictionary.
Input = “Python is easy to Learn”
Output = {‘Pn’: ‘Python’, ‘is’: ‘is’, ‘ey’: ‘easy’, ‘to’: ‘to’, ‘Ln’: ‘Learn’}

26). Python function program to print a list of prime numbers from 1 to 100.

27). Python function program to get a list of odd numbers from 1 to 100.

28). Python function program to print and accept login credentials.

29). Python function program to get the addition with the return statement.

30). Python function program to create a Fruitshop Management system.

31). Python function program to check whether the given year is a leap year.

32). Python function program to reverse an integer.

33). Python function program to create a library management system.

34). Python function program to add two Binary numbers.

35). Python function program to search words in a string.

36). Python function program to get the length of the last word in a string.

37). Python function program to get a valid mobile number.

38). Python function program to convert an integer to its word format.

39). Python function program to get all permutations from a string.

40). Python function program to create a function with **kwargs as parameters.

41). Python function program to create a function local and global variable.

Python Dictionary Practice Programs, Exercises

Python dictionary programs are used to create dictionaries as well as to search for specific entries in them. Dictionaries can be created by assigning key-value pairs for each entry in the program code. This dictionary program in python for practice help user to get expertise in dictionary fundamentals.

1). Python Dictionary program to add elements to the dictionary.

2). Python Dictionary program to print the square of all values in a dictionary.
Input : {‘a’: 5, ‘b’:3, ‘c’: 6, ‘d’ : 8}
Output :
a : 25
b : 9
c : 36
d : 64

3). Python Dictionary program to move items from dict1 to dict2.
Input :
dict1 = {‘name’: ‘john’, ‘city’: ‘Landon’, ‘country’: ‘UK’}
dict2 = {}
Output :
dict1 = {}
dict2 = {‘name’: ‘john’, ‘city’: ‘Landon’, ‘country’: ‘UK’}

4). Python Dictionary program to concatenate two dictionaries.
Input :
dict1 = {‘Name’: ‘Harry’, ‘Rollno’:345, ‘Address’: ‘Jordan’}
dict2 = {‘Age’ : 25, ‘salary’: ‘$25k’}
Output :
dict1 = {‘Name’: ‘Harry’, ‘Rollno’:345, ‘Address’: ‘Jordan’, ‘Age’ : 25, ‘salary’: ‘$25k’}

5)Python Dictionary program to get a list of odd and even keys from the dictionary.
Input :
{1: 25, 5:’abc’, 8:’pqr’, 21:’xyz’, 12:’def’, 2:’utv’}
Output :
Even Key = [[8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
Odd Key = [[1, 25], [5, ‘abc’], [21, ‘xyz’]]

6). Python Dictionary Program to create a dictionary from two lists.
Input :
list1 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]|
list2 = [12, 23, 24, 25, 15, 16]
Output :
{‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15}

7). Python Dictionary program to store squares of even and cubes of odd numbers in a dictionary using dictionary comprehension.
Input :
[4, 5, 6, 2, 1, 7, 11]
Output :
{4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}

8). Python Dictionary program to clear all items from the dictionary.

9). Python Dictionary program to remove duplicate values from Dictionary.
Input :
{‘a’: 12, ‘b’: 2, ‘c’: 12, ‘d’: 5, ‘e’: 35, ‘f’: 5}
Output :
{‘a’: 12, ‘b’: 2, ‘d’: 5, ‘e’: 35}

10). Python Dictionary program to create a dictionary from the string.
Input  = ‘SQATools’
Output{‘S’: 1, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 2, ‘l’: 1, ‘s’: 1}

11). Python Dictionary program to sort a dictionary using keys.
Input = {‘d’ : 21, ‘b’ : 53,  ‘a’: 13, ‘c’: 41}
Output =
(‘a’, 13)
(‘b’, 53)
(‘c’, 41)
(‘d’, 21)

12). Python Dictionary program to sort a dictionary in python using values.
Input = {‘d’ : 14, ‘b’ : 52,  ‘a’: 13, ‘c’: 1 }
Output= (c, 1) (a,13) (d, 14) (b, 52)

13). Python Dictionary program to add a key in a dictionary.
Input= {1:’a’, 2:’b’}
Output= (1:’a’, 2:’b’, 3:’c’}

14). Python Dictionary program to concatenate two dictionaries.
Input:
D1 = {‘name’ : ’yash’, ‘city’ :  ‘pune’}
D1 = {‘course’ : ’python’, ‘institute’ : ’sqatools’}
Output :
{ ‘name’ : ’yash’, city: ‘pune’, ‘course’ : ’python’, ‘institute’ : ’sqatools’ }

15). Python Dictionary program to swap the values of the keys in the dictionary.
Input = {name:’yash’, city: ‘pune’}
Output = {name:’pune’, city: ‘yash’}

16). Python Dictionary program to get the sum of all the items in a dictionary.
Input = {‘x’ : 23, ‘y’ : 10 , ‘z’ : 7}
Output = 40

17). Python program to get the size of a dictionary in python.
Hint : use sys.getsizeof(var) method.
Input = {‘name’ : ’virat’, ‘sport’ : ’cricket’}
Output = 232bytes

18). Python Dictionary program to check whether a key exists in the dictionary or not.
Input:
Dict1 = {city:’pune’, state=’maharashtra’}
Dict1[country]
Output= ‘key does not exist in dictionary

19). Python program to iterate over a dictionary.
Input :
Dict1 = {food:’burger’, type:’fast food’}
Output :
food : burger
type : fast food

20). Python Dictionary program to create a dictionary in the form of (n^3) i.e. if key=2 value=8
Input: n=4
Output ={1 : 1, 2 : 8, 3 : 27, 4 : 64}

21). Python Dictionary program to insert a key at the beginning of the dictionary.
Input = { ‘course’ : ’python’,  ‘institute’ : ’sqatools’ }
Insert : ( ‘name’ : ’omkar’ )
Output= { ‘name’ : ’omkar’, ‘course’ : ’python’, ‘institute’ : ’sqatools’}

22). Python Dictionary  program to create a dictionary where keys are between 1 to 5 and values are squares of the keys.
Output ={1 : 1, 2 : 4, 3 : 9, 4 : 16, 5 : 25}

23). Python Dictionary program to find the product of all items in the dictionary.
Input = { ‘a’ : 2, ‘b’ : 4, ‘c’ : 5}
Output = 40

24). Python Dictionary program to remove a key from the dictionary.
Input = {a:2,b:4,c:5}
Output = (a:1,b:4}

25). Python Dictionary program to map two lists into a dictionary.
Input
a = [ ‘name’, ‘sport’, ‘rank’, ‘age’]
b = [‘Virat’, ‘cricket’, 1,  32]
Output =  { ‘name’ : ’virat’, ‘sport’ : ’cricket’, ‘rank’: 1, ‘age’ : 32}

26). Python Dictionary program to find maximum and minimum values in a dictionary.
Input :
Dict = { ‘a’ : 10, ‘b’ : 44 , ‘c’ : 60, ‘d’ : 25}
Output :
Maximum value: 60
Minimum value: 10

27). Python Dictionary program to group the same items into a dictionary value.
Input :
list = [1,3,4,4,2,5,3,1,5,5,2,]
Output = {1 : [1, 1], 2 :[2, 2], 3 : [3, 3], 4 : [4, 4], 5 : [5, 5, 5]}

28). Python Dictionary program to replace words in a string using a dictionary.
String = ’learning python at sqa-tools’
Dict = { ‘at’ : ’is’, ‘sqa-tools’ : ’fun’}
Output = ‘learning python is fun’

29). Python Dictionary program to remove a word from the string if it is a key in a dictionary.
String = ’sqatools is best for learning python’
Dict = { ‘best’ : 2, ‘learning’ : 6}
Output = “sqatools is for python”

30). Python Dictionary program to remove duplicate values from dictionary values.
Input:
Dict1 = { ‘marks1’ : [23,28,23,69], ‘marks2’ : [ 25, 14,25] }
Output= { ‘marks1’ : [28, 69], ‘marks2’ : [14,19] }

31). Python Dictionary program to check whether a dictionary is empty or not.
Input:
Dict1 = {}
Output: Given dictionary is empty

32). Python Dictionary program to add two dictionaries if the keys are the same then add their value.
Input:
Dict1 = { ‘x’:10, ‘y’:20, ‘c’:50, ‘f’:44 }
Dict2 = {‘x’:60,’c’:25,’y’:56}
Output = {‘x’: 70, ‘c’: 75, ‘y’: 76}

33). Python Dictionary program to print all the unique values in a dictionary.
Input :
Dict1 = [{name1:’robert’},  {name2:’john’}, {name3:’jim’}, {name4:’robert’}]
Output = [‘robert’, ’john’, ’jim’]

34). Python Dictionary program to display different combinations of letters from dictionary values.
Input:
Dict1 = { x:[e,f], y:[a,b]}
Output: 
  ea
  eb
  fa
  fb

35). Python Dictionary program to create a dictionary from a string.
Input = ‘sqatools’
Output = {s:2,q:1,a:1, t:1,o:2, l:1}

36). Python Dictionary program to print the given dictionary in the form of tables.
Input:
Dict1= {names:[‘virat’,’messi’,’kobe’], sport:[‘cricket’,’football’,’basketball’]}
Output:
     Names   sport
0    Virat      cricket
1    Messi     football
2    Kobe      basketball

37). Python program to count frequencies in a list using a dictionary.
Input:
list1= [2,5,8,1,2,6,8,5]
Output = {1:1,2:2, 5:2, 6:1, 8:2}

38). Python program to find mean of values of keys in a dictionary.
Input :
Dict1= {m1:25, m2:20, m3:15}
Output :
Mean is 20

39). Python program to convert a list into a nested dictionary of keys.
Input = [a,b,c,d]
Output = {a: {b: {c: {d: {}}}}}

40). Python program to sort a list of values in a dictionary.
Input= { a1 : [1,5,3], a2 : [10,6,20] }
Output= ( a1 : [1,3,5], a2 : [6,10,20] }

41). Python program to get a product with the highest price from a dictionary.
Input = { ‘price1’ : 450, ‘price2‘ : 600,  ‘price3′ : 255,  ‘price4′ : 400}
Output = P2 500

42). Python program to print a dictionary line by line.
Input = {‘virat’: {sport:’cricket’, team:’india’}, ‘messi’: {sport:’football’, team:’argentina’}}
Output=
Virat
Sport : cricket
Team : india

Messi
Sport : football
Team : argentina

43). Python program to convert a key value list dictionary into a list of list.
Input = {sqa:[1,4,6], tools:[3,6,9]}
Output= [[sqa,1,4,6],[tools,3,6,9]]

44). Python program to convert a list of dictionaries to a list of lists.
Input= [{‘sqa’:123,’tools’:456}]
Output= [[sqa],[tools],[123],[456]]

45). Python program to count a number of items in a dictionary value that is in a list.
Input = {‘virat’:[‘match1’,match2’,’match3’], ‘rohit’:[‘match1’,’match2’]}
Output= 5

46). Python program to sort items in a dictionary in descending order.
Input = {‘Math’:70, ‘Physics’:90, ‘Chemistry’:67}
Output = {‘Physics’:90, ’Maths’:70, ’Chemistry’:67}

47). Python program to replace dictionary values with their average.
Input = { name:’ketan’, subject:’maths’, p1:80, p2:70}
Output = { name:’ketan’,subject:’maths’, p1+p2:75}

48). Python program to match key values in two dictionaries.
Input
A = {‘k1’: p, ‘k2’: q, ‘k3’: r}
B = {‘k1’: p, ‘k2’: s}

Output = k1: p is present in both A and B

49). Python program to create a dictionary of keys a, b, and c where each key has as value a list from 1-5, 6-10, and 11-15 respectively. 
Output = { a: [1,2,3,4,5],  b: [6,7,8,9,10],  c: [11,12,13,14,15] }

50). Python program to drop empty Items from a given dictionary.
Input = {‘m1’:40, ‘m2’:50, ‘m3’:None}
Output = {‘m1’:40, ‘m2’:50}

51). Python program to filter a dictionary based on values.
Input{ ‘alex’ : 50,  ‘john’ : 45, ‘Robert’ : 30}
Output= value greater than 40
{alex:50, john:45}

52). Python program to convert a key-values list to a flat dictionary.
Input = {‘name’: [‘Apr’, ‘May’, ‘June’], ‘month’: [4, 5, 6]}
Output ={‘Apr’: 4, ‘May’: 5, ‘June’: 6}

53). Python program to convert a list of Tuples into a dictionary
Input =  [(“mike”, 1), (“Sarah”, 20), (“Jim”, 16)]
Output{“mike”:1, “Sarah”:20, “Jim”:16}

54). Python program to convert string to the dictionary.
Input:
str1= “Apr=April; Mar=March”
Output: {‘Apr’: ‘April’, ‘ Mar’: ‘March’}

55). Python program to convert a matrix into a dictionary.
Input = [[1,2,3],[4,5,6]]
Output{1 : [1,2,3] , 2 : [4,5,6]}

56). Python program to check all values are the same in a dictionary.
Input :
A={‘virat’:50, ’rohit’:50, ’rahul’:50, ’hardik’:50}    
OutputTrue

57). Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists.
Input :
A= {‘virat’:50, ’rohit’:40, ’virat’:30, ’rohit’:10}
Output{‘virat’:[50,30],’rohit’:[40,10]}

58). Python program to split a given dictionary of lists into list of dictionaries.
Input :
A={ ‘t20’ : [50,40,30,45], ‘odi’ : [70,10,0,65] }
Output :
[ {t20:50, odi:70} ,{t20:40, odi:10}, {t20:30, odi:0}, {t20:45, odi:65} ]

59). Python program to remove a specified dictionary from a given list.
Input = [ { t20:50, odi:70 }, { t20:40, odi:10 }, { t20:30,odi:0 }, { t20:45, odi:65} ]
Remove 4th dictionary
Output=[ { t20:50, odi:70 }, { t20:40, odi:10 } ,{ t20:30, odi:0 } ]

60). Python program to convert string values of a given dictionary, into integer/float datatypes.
Input :
A = { ‘a’: ’30’,  ‘b’: ’20’, ‘c: ’10’ } 
B=  { ‘a’: ‘3.33’, ‘b’: ‘20.50’, ‘c: ‘12.5’ }
Output
A = { ‘a’: 30, ‘b’: 20, ‘c: 10 } 
B = { ‘a’: 3.33, ‘b’: 20.50, ‘c: 12.5 } 

61).  A Python dictionary contains a list as a value. Python program to clear the list values in the said dictionary.
Input={‘virat’:[50,30],’rohit’:[40,10]} 
Output{ ‘virat’: [], ’rohit’: [] }

62). A Python dictionary contains list as value. Python program to update the list values in the said dictionary.
Input{ ‘virat’ : [ 50,30 ], ’rohit’ : [ 40,10 ] }
Output ={‘virat’: [60, 40], ‘rohit’: [15, -15]}

63). Python program to extract a list of values from a given list of dictionaries
Input:
A=[ { t20:50, odi:70 }, { t20:40, odi:10 }, { t20:30, odi:0 }, { t20:45, odi:65 } ]
Extract values for ‘odi’
Output = [70,10,0,65]

64). Python program to find the length of dictionary values.
Input = { 1:’sqa’, 2:’tools’, 3:’python’ }
Output{ ‘sqa’:3, ’tools’:5, ‘python’:6 }

65). Python program to get the depth of the dictionary.
Input = {‘a’:1, ‘b’: {‘c’: {‘d’: {}}}}
Output4

66). Python program to create nested Dictionary using List.
Input = {‘sqatools’:8,’python’:6} list=[1,2]
Output{ 1: { sqatools’:8 }, 2:[‘python’:6] }

67). Python program to extract key’s value if key is present in list and dictionary
Input:
A = [‘sqatools’,’is’,’best’]
B = {‘sqatools’:10}
Output = 10

68). Python program to remove keys with values greater than n.
Input { ‘sqa’:3, ’tools’:5, ‘python’:7 } 
n=6
Output{‘sqa’:3,’tools’:5}

69). Python program to remove keys with substring values.
Input :
D1 = { 1:’sqatools is best’, 2: ’for learning python’}
Substr = [‘best’,’ excellent’]
Output{ 2:  ’for learning python’ }

70). Python program to access the dictionary key.
Input :
Drinks = { pepsi:50, sprite:60, slice:55}
Output:
Pepsi
Sprite
Slice

71). Python program to filter even numbers from a given dictionary value.
Input = { ‘a’: [11, 4, 6, 15],  ‘b’: [3, 8, 12],  ‘c’: [5, 3, 10] }
Output{ ‘a’:[4,6], ’b’:[8,12],  ’c’:[10] }

72). Python program to find the keys of maximum values in a given dictionary.
Input = { a:18, b:50, c:36, d:47, e:60 }
Find keys of first 2 max values from the dictionary
Output[ e, b ]

73). Python program to find the shortest list of values with the keys in a given dictionary.
Input{ ‘a’: [10, 12], ‘b’: [10],  ‘c’: [10, 20, 30, 40], ‘d’: [20] }
Output[ ‘b’, ’d’ ]

74). Python program to count the frequency in a given dictionary.
Input = { a:10, b:20, c:25, d:10, e:30, f:20 }
Output{ 10:2, 20:2, 25:1, 30:1}

75). Python program to create key-value list pairings in a given dictionary.
Input{ 1: [‘Virat Kohli’], 2: [‘Rohit Sharma’], 3: [‘Hardik Pandya’] }
Output[ { 1: ‘Virat Kohli’, 2: ‘Rohit Sharma’, 3: ‘Hardik Pandya’ } ]

76). Python program to get the total length of a dictionary with string values.
Input = { ‘virat’:50,’Rohit’:40,’Rahul’:25 }
Output :
Total length: 6

77). Python program to group the elements of a given list based on the given function.
Hint : Function name: len()
Input[‘abc’, ‘defg’, ‘hijkl’]
Output{ 3:[‘abc’],  4:[‘defg’], 5:[‘hijkl’] }

78). Python program to retrieve the value of the nested key indicated by the given selector list from a dictionary or list.
Input = {‘p1’:{name:{first:lionel, last:messi}, team:[psg,argentina]}}
Output :
Messi
Argentina

79). Python program to show a dictionary with a maximum count of pairs.
Input:
A = {name:1,age:2}
B = {name:1,age:2,course:3,institute:4}
Output:
2nd dictionary has maximum keys, 4

80). Python program to Extract Unique values from dictionary values.
Input = { sqa:[1,2,5,6],tools:[3,8,9],is:[2,5,0],best:[3,6,8] }
Output[0,1,2,3,5,6,8,9]

81). Python program to show keys associated with values in dictionary
Input = { ‘xyz’:[20,40], abc:[10,20] }
Output ={20: [‘xyz’], 40: [‘xyz’], 10: [‘abc’], 30: [‘abc’]}

82). Python program to convert a list of dictionaries into a list of values corresponding to the specified key.
Input = [ { name:’jos’,  age:30 }, { name:’david’, age:25 }, { name:’virat’, age:32 } ]
Output = [30, 25, 32]

83). Python program to find all keys in the provided dictionary that have the given value.
Input = {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20}
value = 20
Output = [‘b’, ‘d’]

84). Python program to convert given a dictionary to a list of tuples.
Input = {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20}
Output =[ (a,19), (b,20), (c,21), (d,20) ]

85). Python program to create a flat list of all the keys in a flat dictionary.
Input = { ‘sqa’: [1,2,5,6], ‘tools’: [3,8,9], ‘is’: [2,5,0], ‘best’ : [3,6,8] } 
Output = [ sqa, tools, is, best]

86). Python program to create a flat list of all the values in a flat dictionary. 
Input = { sqa:1, tools:2, is:2, best:4 } 
Output =[ 1,2,3,4 ]

87). Python program to initialize a dictionary with default values.
Name = [ ”Virat”, ”Rohit” ]
Defaults = { ‘sport’ : ’cricket’, ‘salary’ : 100000 }
Output = { “Virat” : { sport: ’cricket’, salary:100000 }, “Rohit”:{ sport: ’cricket’, salary:10000}}

88). Python program to delete a list of keys from a dictionary.
Input = { ‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20, ‘e’: 50 }
Keys to be removed:  [ ‘a’, ‘d’, ‘e’ ]
Output = { ‘b’: 20, ‘c’: 21 }

89). Python program to rename key of a dictionary
Input = { ‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20}
Output = { ‘a’: 19, ‘b’: 20, ‘c’: 21, ‘e’: 20}

90). Python program to Invert a given dictionary with non-unique hashable values.
Input = { ‘alex’:1, ’bob’:2,’ martin’:1, ’robert’:2 }
Output = { 1:[‘alex’,’marin’], 2:[‘bob’,’robert’] }

91). Python program to Sort Dictionary by values summation
Input = { x:[1,5,6], y:[4,8,2], c:[3,9] }
Output = { c:12, x:12, y:14}

92). Python program to convert a dictionary into n sized dictionary.
Input = { a:1, b:2, c:3, d:4, e:5, f:6 }
N = 3
Output = [{ a:1, b:2, c:3 }, {d:4, e:5, f:6}]

93). Python program to Sort dictionaries list by Key’s Value list index
Input = [ { a:[ 6, 7, 8],  b:9, c : 10 }, { a : [4, 6, 9],  b: 16, c : 1 } ]
Key = a,  index=0
Output = [ { a : [4, 6, 9],  b: 16, c : 1}, {a: [ 6, 7, 8],  b:9, c : 10} ]…

94) Python program to reverse each string value in the dictionary and add an underscore before and after the Keys.
Input  = {“a” : “Python”, “b”: “Programming”, “c”: “Learning”}
Output = {“_a_”: “nythonP”, “_b_” : “gnimmargorP”, “_c_”: “gearninL”}

95). Python program to sum unique elements from dictionary list values.
Input = { ‘a’ : [ 6, 7, 2, 8, 1], ‘b’ : [2, 3, 1, 6, 8, 10], ‘d’ : [1, 8, 2, 6, 9] }
Output :
46

Python List Programs, Exercises

Python list programs help beginners to become experts and the list is one of the most important data structures in Python Programming. Python list can contain any type of data as a member that we can access via positive and negative indexing.

In this article, we have two different sections one for Python list programs for beginners and the second for Python list projects for practice.

python list programs

Python List Programs

1). Python program to calculate the square of each number from the given list.

2). Python program to combine two lists.

3). Python program to calculate the sum of all elements from a list.

4). Python program to find a product of all elements from a given list.

5). Python program to find the minimum and maximum elements from the list.

6). Python program to differentiate even and odd elements from the given list.

7). Python program to remove all duplicate elements from the list.

8). Python program to print a combination of 2 elements from the list whose sum is 10.

9). Python program to print squares of all even numbers in a list.

10). Python program to split the list into two-part, the left side all odd values and the right side all even values.
Input = [5, 7, 2, 8, 11, 12, 17, 19, 22]
Output = [5, 7, 11, 17, 19, 2, 8, 12, 22]

11).  Python program to get common elements from two lists.
Input =
list1 = [4, 5, 7, 9, 2, 1]
list2 = [2, 5, 8, 3, 4, 7]
Outputt : [4, 5, 7, 2]

12). Python program to reverse a list with for loop.

13). Python program to reverse a list with a while loop.

14). Python program to reverse a list using index slicing.

15). Python program to reverse a list with reversed and reverse methods.

16). Python program to copy or clone one list to another list.

17). Python program to return True if two lists have any common member.

18). Python program to print a specific list after removing the 1st, 3rd, and 6th elements from the list.

19). Python program to remove negative values from the list.

20). Python program to get a list of all elements which are divided by 3 and 7.

21). Python program to check whether the given list is palindrome or not. (should be equal from both sides).

22). Python Program to get a list of words which has vowels in the given string.
Input: “www Student ppp are qqqq learning Python vvv”
Output : [‘Student’, ‘are’, ‘learning’, ‘Python’]

23). Python program to add 2 lists with extend method.

24). Python program to sort list data, with the sort and sorted method.

25). Python program to remove data from the list from a specific index using the pop method.

26). Python program to get the max, min, and sum of the list using in-built functions.

27). Python program to check whether a list contains a sublist.

28). Python program to generate all sublists with 5 or more elements in it from the given list.

29). Python program to find the second largest number from the list.
 

30). Python program to find the second smallest number from the list.

31). Python program to merge all elements of the list in a single entity using a special character.
 

32). Python program to get the difference between two lists.

33). Python program to reverse each element of the list.
Input = [‘Sqa’, ‘Tools’, ‘Online’, ‘Learning’, ‘Platform’]
output = [‘aqS’, ‘slooT’, ‘enilno’, ‘gninraeL’, ‘mroftalP’]
34). Python program to combine two list elements as a sublist in a list.
list1 = [3, 5, 7, 8, 9]
list2 = [1, 4, 3, 6, 2]
Output = [[3, 1], [5, 4], [7, 3], [8, 6], [9, 2]]
35). Python program to get keys and values from the list of dictionaries.
Input : [{‘a’:12}, {‘b’: 34}, {‘c’: 23}, {‘d’: 11}, {‘e’: 15}]
Output :  [‘a’, ‘b’, ‘c’, ‘d’, ‘c’]
                [12, 34, 23, 11, 15]

36). Python program to get all the unique numbers in the list.

37). Python program to convert a string into a list.

38). Python program to replace the last and the first number of the list with the word.
Input: [12, 32, 33, 5, 4, 7]
output : [‘SQA’, 32, 33, 5, 4, ‘Tools’]
 

39). Python program to check whether the given element is exist in the list or not.

40). Python program to remove all odd index elements.
Input: [12, 32, 33, 5, 4, 7, 33]
Output: [12,33,4,33]

41). Python program to take two lists and return true if then at least one common member.

42). Python program to convert multiple numbers from a list into a single number.
Input: [12, 45, 56]
Output:124556
43). Python program to convert words of a list into a single string.
Input: [‘Sqa’, ‘Tools’, ‘Best’, ‘Learning’, ‘Platform’]
Output: SqaToolsBestLearningPlatform
44). Python program to print elements of the list separately.
Input: [(‘Black’, ‘Yellow’, ‘Blue’), (50, 55, 60), (30.0, 50.5, 55.66)]
Output:
(‘Black’, ‘Yellow’, ‘Blue’)
(50, 55, 60)
(30.0, 50.5, 55.66)
45). Python program to create a sublist of numbers and their squares from 1 to 10.
Output : [[1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81], [10, 100]]
46). Python program to create a list of five consecutive numbers in the list.
Output : [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
47). Python program to insert a given string at the beginning of all items in a list.
Input: [1, 2, 3, 4, 5], Sqa
Output: [‘Sqa1’, ‘Sqa2’, ‘Sqa3’, ‘Sqa4’, ‘Sqa5’]
48). Python program to iterate over two lists simultaneously and create a list of sublists.
list1 = [1, 3, 5, 7, 9]
list2 = [8, 6, 4, 2, 10]
output = [[1, 8], [3, 6], [5, 4], [7, 2], [9, 10]]
49). Python program to move all positive numbers on the left side and negative numbers on the right side.
Input: [2, -4, 6, 44, -7, 8, -1, -10]
Output: [2, 6, 44, 8, -4, -7, -1, -10]
50). Python program to move all zero digits to the end of a given list of numbers.
Input: [3, 4, 0, 0, 0, 0, 6, 0, 4, 0, 22, 0, 0, 3, 21, 0]
Output: [3, 4, 6, 4, 22, 3, 21, 0, 0, 0, 0, 0, 0, 0, 0]
51). Python program to find the list in a list of lists whose sum of elements is the highest.
Input: [[11, 2, 3], [4, 15, 6], [10, 11, 12], [7 8, 19]]
Output: [7, 8, 19]
52). Python program to find the items that start with a specific character from a given list.
Input: [‘abbcd’, ‘ppq, ‘abdd’, ‘agr’, ‘bhr’, ‘sqqa’, tools, ‘bgr’]
 
# item starts with a from the given list.
[‘abbcd’, ‘abdd’, ‘agr’]
 
# item starts with b from the given list.
[‘bhr’, ‘bgr’]
 
# item starts with c from the given list.
[]
53). Python program to count empty dictionaries from the given list.
Input: [{}, {‘a’: ‘sqatools’}, [], {}, {‘a’: 123}, {},{},()]
empty_count: 3
54). Python program to remove consecutive duplicates of given lists.
Input: [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4]
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 4]
55). Python program to pack consecutive duplicates of given list elements into sublists.
Input: [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]
Output: [[0, 0], [1], [2], [3], [4, 4], [5], [6, 6], [7], [8, 8], [9]]
56). Python program to split a given list into two parts where the length of the first part of the list is given.
Input: [4, 6, 7, 3, 2, 5, 6, 7, 6, 4]
length of the first part is 4
Output: [[4, 6, 7, 3], [2, 5, 6, 7, 6, 4]]
57). Python program to insert items at a specific position in the list.
Input: [2, 4, 6, 8, 3, 22]
Index: 3
Item: 55
Output: [2, 4, 6, 55, 8, 3, 22]
58). Python program to select random numbers from the list.
Input: [1, 4, 5, 7, 3, 2, 9]
Selected 4 random numbers from the list.
59). Python program to create a 3*3 grid with numbers.
Output: [[4, 5, 6], [4, 5, 6], [4, 5, 6]]
60). Python program to zip two lists of lists into a list.
list1: [[1, 3], [5, 7], [9, 11]]
list2: [[2, 4], [6, 8], [10, 12, 14]]
61). Python program to convert the first and last letter of each item from Upper case and lowercase.
Input: [‘Learn’, ‘python’, ‘From’, ‘Sqa’, tools]
Output =
[‘LearN ‘, ‘PythoN ‘, ‘FroM ‘, ‘SqA ‘, ‘ToolS ‘]
[‘learn ‘, ‘python ‘, ‘from ‘, ‘sqa ‘, ‘tools ‘]
62). Python to find maximum and minimum values in the given heterogeneous list.
Input: [‘Sqa’, 6, 5, 2, ‘Tools’]
Output: [6,2]
63). Python program to sort a given list in ascending order according to the sum of its sublist.
Input: [[3, 5, 6], [2, 1, 3], [5, 1, 1], [1, 2, 1], [0, 4, 1]]
            14         6         7           4          5
Output = [[1, 2, 1], [0, 4, 1], [2, 1, 3], [5, 1, 1], [3, 5, 6]]
64). Python program to extract the specified sizes of strings from a given list of string values.
Input: [‘Python’, ‘Sqatools’, ‘Practice’, ‘Program’, ‘test’, ‘list’]
size = 8
Output: [‘Sqatools’, ‘Practice’]
65). Python program to find the difference between consecutive numbers in a given list.
Input list: [1, 1, 3, 4, 4, 5, 6, 7]
Output list: [0, 2, 1, 0, 1, 1, 1]
66). Python program to calculate the average of the given list.
Input : [3, 5, 7, 2, 6, 12, 3]
Output: 5.428571428571429
67). Python program to count integers in a given mixed list.
Input list: [‘Hello’, 45, ‘sqa’,  23, 5, ‘Tools’, 20]
Output: 4
68). Python program to access multiple elements of the specified index from a given list.
Input list: [2, 3, 4, 7, 8, 1, 5, 6, 2, 1, 8, 2]
Index list: [0, 3, 5, 6]
Output: [2, 7, 1, 5]
69). Python program to check whether a specified list is sorted or not.
Input list : [1, 2, 3, 5, 7, 8, 9]
Output: True
 
Input list: [3, 5, 1, 6, 8, 2, 4]
Output: False
70). Python program to remove duplicate dictionaries from a given list.
Input : [{‘name’: ‘john’}, {‘city’: ‘mumbai’}, {‘Python’: ‘laguage’}, {‘name’: ‘john’}]
Output: [{‘city’: ‘mumbai’}, {‘Python’: ‘laguage’}]
71). Python program to check if the elements of a given list are unique or not.
Input: [2, 5, 6, 7, 4, 11, 2, 4, 66, 21, 22, 3]
Output: False
72). Python program to remove duplicate sublists from the list.
Input: [[1, 2], [3, 5], [1, 2], [6, 7]]
Output: [[3, 5],[6, 7]]
73). Python program to create a list by taking an alternate item from the list.
Input: [3, 5, 7, 8, 2, 9, 3, 5, 11]
Output: [3, 7, 2, 3, 11]
74). Python program to remove duplicate tuples from the list.
Input: [(2, 3), (4, 6), (5, 1), (2, 3), (7, 9), (5, 1)]
Output: [(2,3), (4, 6), (5,1), (7, 9)]
75). Python program to insert an element before each element of a list.
Input :[3, 5, 7, 8]
element = ‘a’
Output: [‘a’, 3, ‘a’, 5, ‘a’, 7, ‘a’, 8]
76). Python program to remove the duplicate string from the list.
Input: [‘python’, ‘is’, ‘a’, ‘best’, ‘language’, ‘python’, ‘best’]
Output: [‘python’, ‘is’, ‘a’, ‘best’, ‘language’]

77). Python program to get the factorial of each item in the list.

78). Python program to get a list of Fibonacci numbers from 1 to 20.

79). Python program to reverse all the numbers in a given list.
Input : [123, 145, 633, 654, 254]
Output: [321, 541, 336, 456, 452]
80). Python program to get palindrome numbers from a given list.
Input : [121, 134, 354, 383, 892, 232]
Output : [121, 282, 232]
81). Python program to get a count of vowels in the given list.
Input : [‘Learning’, ‘Python’, ‘From’, ‘SqaTool’]
Output : 8
82). Python program to get the list of prime numbers in a given list.
Input : [11, 8, 7, 19, 6, 29]
Output : [11,  7,  19, 29]
83). Python program to get a list with n elements removed from the left and right.
Input : [2, 5, 7, 9, 3, 4]
Remove 1 element from left
[5, 7, 9, 3, 4]
 
Remove 1 element from the right
[2, 5, 7, 9, 3]
 
Remove 2 elements from left
[7, 9, 3, 4]
 
Remove 2 elements from right
[2, 5, 7, 9]
84). Python program to create a dictionary with two lists.
Input :
list1 : [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
list2 : [234, 123, 456, 343, 223]
Output: {‘a’: 234, ‘b’: 123, ‘c’: 456, ‘d’: 343, ‘e’: 223}
85). Python program to remove the duplicate item from the list using set.
Input : [2, 5, 7, 8, 2, 3, 4, 12, 5, 6]
Output : [2, 5, 7, 8, 3, 4, 12, 6]
86). Python program to insert a sublist into the list at a specific index.
Input : [4, 6, 8, 2, 3, 5]
sublist, index
[5, 2, 6], 3
Output: [4, 6, 8, [5, 2, 6], 2, 3, 5]
87). Python program to calculate the bill per fruit purchased from a given fruits list.
Input =
Fruit list with Price: [[‘apple’, 30], [‘mango’, 50], [‘banana’, 20], [‘lichi’, 50]]
Fruit with quantity: [[‘apple’, 2]]
Output =
Fruit: Apple
Bill: 60
Fruit: mango
Bill: 500
88). Python program to calculate percentage from a given mark list, the max mark for each item is 100.
Marks_list : [80, 50, 70, 90, 95]
Output: 77%
89). Python program to get the list of all palindrome strings from the given list.
Input: [‘data’, ‘python’, ‘oko’, ‘test’, ‘ete’]
Output: [‘oko’, ‘ete’]
90). Python program to flatten a given nested list structure.
Input: [0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]
Output: [0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]
91). Python program to convert tuples in the list into a sublist.
Input: [(3, 5), (6, 8), (8, 11), (12, 14), (17, 23)]
Output: [[3, 5], [6, 8], [8, 11], [12, 14], [17, 23]]
92). Python program to create a dictionary from a sublist in a given list.
Input: [[‘a’, 5], [‘b’, 8], [‘c’, 11], [‘d’, 14], [‘e’, 23]]
Output: {‘a’: 5, ‘b’: 8, ‘c’: 11, ‘d’: 14, ‘e’: 23}
93). Python program to replace ‘Java’ with ‘Python’ from the given list.
Input: [‘Hello’, ‘student’, ‘are’, ‘learning’, ‘Python’, ‘Its’, ‘Python’, ‘Language’]
Output: [‘Hello’, ‘student’, ‘are’, ‘learning’, ‘Java’, ‘Its’, ‘Java’, ‘Language’]
94). Python program to convert the 3rd character of each word to a capital case from the given list.
Input: [‘Hello’, ‘student’, ‘are’, ‘learning’, ‘Python’, ‘Its’, ‘Python’, ‘Language’]
Output: [‘HelLo’, ‘stuDent’, ‘are’, ‘leaRning’, ‘PytHon’, ‘Its’, ‘PytHon’, ‘LanGuage’]
95). Python program to remove the 2nd character of each word from a given list.
Input: [‘Hello’, ‘student’, ‘are’, ‘learning’, ‘Python’, ‘Its’, ‘Python’, ‘Language’]
Output[‘Hllo’, ‘sudent’, ‘ae’, ‘larning’, ‘Pthon’, ‘Is’, ‘Pthon’, ‘Lnguage’]
96). Python program to get a length of each word and add it as a dictionary from the given list.
Input: [‘Hello’, ‘student’, ‘are’, ‘learning’, ‘Python’, ‘Its’, ‘Language’]
Output: [{‘Hello’:5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3, ‘Language’: 8}]
97). Python program to remove duplicate dictionaries from the given list.
Input: [{‘Hello’:5}, {‘student’: 7}, {‘are’: 3}, {‘learning’: 8}, {‘Hello’:5}, ,{‘Language’: 8}, {‘are’: 3}]
Output: [{‘Hello’:5, ‘student’: 7, ‘are’: 3, ‘learning’: 8, ‘Python’: 6, ‘Its’: 3, ‘Language’: 8}]
98). Python program to decode a run-length encoded given list.
Input: [[2, 1], 2, 3, [2, 4], 5, 1]
Output: [1, 1, 2, 3, 4, 4, 5, 1]
99). Python program to round every number in a given list of numbers and print the total sum of the list.
Input: [22.4, 4.0, -16.22, -9.1, 11.0, -12.22, 14.2, -5.2, 17.5]
Output: 27
 
list1 = [2, 4, 6, 7, 5, 8, 3, 11]

result = [x**2 for x in list1 if x%2 == 0]

print("Result :", result)

Output :

Result : [4, 16, 36, 64]

100).  Python Program to get the Median of all the elements from the list.
list1 = [2, 4, 6, 7, 5, 8, 3, 11]

result = [x**2 for x in list1 if x%2 == 0]

print("Result :", result)

Output :

Result : [4, 16, 36, 64]

101). Python Program to get the Standard deviation of the list element.
102). Python program to convert all numbers to binary format from a given list.
103). Python program to convert all the numbers into Roman numbers from the given list.

Python Lists Project Ideas

1). To-do List: Python list program that allows users to create and manage their to-do lists. Users can add, delete, and update tasks on their list.  Each task can add along with a unique id which will first element of each sub-list through which the user can easily identify the item and task.

2). Shopping List: A program that allows users to create and manage their shopping list. Users can add, delete, and update items on their list. There are many Python list programs listed above those can help user to solve this project.

3). Game Leaderboard: A program that keeps track of scores for multiple players in a game. Use Python lists to store the scores and display a leaderboard of the top players. Nowadays people like to play games and users can apply a basic understanding of Python list programs to write code for this mini-project. 

4). Student Gradebook: A Python list program that allows teachers to enter and manage student grades. Use Python lists and sub-lists to store student names and their corresponding grades.

5). Password Manager: A program that securely stores and manages passwords using Python lists. Users can add, delete, and update passwords, and the program can encrypt the data for added security, Its good exercises to apply understanding Python list programs. 

6). Music Library: A Python list program that allows users to create and manage a music library. Users can add, delete, and update songs, artists, and album details in the list.

7). Recipe Book: A program that allows users to create and manage their recipe book. Users can add, delete, and update recipes, ingredients, and cooking instructions.

8). Contact List: A Python list program that allows users to manage their contact list. Users can add, delete, and update contacts’ names, phone numbers, and email addresses in the list.

9). Movie Library: A Python list program that allows users to create and manage a movie library. Users can add, delete, and update movies, actors, and directors in the list.

10). Sports Team Roster: A program that allows coaches to manage their sports team roster. Coaches can add, delete, and update players’ names, positions, and statistics in the list.

Official reference for python list data structure