Core Python - Module 8 - 11
Core Python - Module 8 - 11
1. Creating Strings
In Python, strings can be created in several ways, depending on the use case and formatting
needs. Here’s an overview of different methods for creating strings:
Triple quotes (''' or """) are used for creating multi-line strings.
multi_line_string = '''This is
a multi-line
string.'''
3. Concatenating Strings
first = "Hello"
second = "World"
concatenated_string = first + " " + second # Output: "Hello
World"
number = 123
string_number = str(number) # Output: "123"
7. String Interpolation
name = "Alice"
age = 25
greeting = f"My name is {name} and I am {age} years old."
b. format() Method
Raw strings (r or R) are used to prevent escape sequences from being interpreted.
To avoid escaping quotes within a string, you can mix quotes or use escape sequences.
For binary data, you can create a byte string with the b prefix.
name = "Bob"
multi_line_f_string = f"""Hello, {name},
Welcome to Python!"""
2. Length of a String
To determine the length of a string in Python, you can use the built-in len() function. This
function returns the number of characters in the string, including spaces, punctuation, and special
characters.
Syntax
len(string)
Example
# Example 1: Basic string
text = "Hello, World!"
print(len(text)) # Output: 13
Escape sequences count as one character: Escape sequences like \n (newline) or \t (tab)
count as a single character.
string_with_escape = "Hello\nWorld"
print(len(string_with_escape)) # Output: 11
Special characters count: Symbols and punctuation are included in the length.
special_string = "!@#$%^&*()"
print(len(special_string)) # Output: 10
Use Cases
3. Indexing in Strings
Indexing in Strings allows you to access individual characters in a string based on their
position. In Python, strings are indexed arrays of characters, starting at 0 for the first character.
Both positive and negative indexing are supported.
1. Positive Indexing
● Starts from 0 (first character) to n-1 (last character), where n is the string length.
● Syntax: string[index]
text = "Python"
print(text[0]) # Output: 'P' (first character)
print(text[3]) # Output: 'h' (fourth character)
print(text[5]) # Output: 'n' (last character)
2. Negative Indexing
text = "Python"
print(text[-1]) # Output: 'n' (last character)
print(text[-3]) # Output: 'h' (third-last character)
print(text[-6]) # Output: 'P' (first character)
3. Accessing Substrings
text = "Code"
for i in range(len(text)):
print(f"Index {i}: {text[i]}")
Output:
Index 0: C
Index 1: o
Index 2: d
Index 3: e
5. IndexError
text = "Hello"
print(text[10]) # Raises IndexError: string index out of range
6. Immutable Strings
Strings in Python are immutable, meaning you cannot change a character directly by indexing.
text = "Python"
# text[0] = 'J' # This will raise TypeError
String Slicing in Python allows you to extract a substring by specifying a range of indices. The
slicing syntax uses the colon : operator to define the start, stop, and step for selecting
characters.
1. Syntax
substring = string[start:stop:step]
● start: The index where the slice begins (inclusive, default is 0).
● stop: The index where the slice ends (exclusive).
● step: The interval between characters (default is 1).
2. Basic Examples
3. Step Value
text = "Python"
# Positive step
print(text[::2]) # Output: 'Pto' (every 2nd character)
# Custom step
print(text[1:6:2]) # Output: 'yh' (indices 1, 3, 5)
4. Omitting Parameters
● start defaults to 0.
● stop defaults to the string length.
● step defaults to 1.
text = "Programming"
print(text[:]) # Output: 'Programming' (entire string)
print(text[::2]) # Output: 'Pormig' (every 2nd character)
print(text[::-1]) # Output: 'gnimmargorP' (reversed string)
5. Negative Slicing
Negative indices and steps are helpful for slicing from the end or reversing.
text = "Python"
# Negative indices
print(text[-6:-3]) # Output: 'Pyt' (indices -6 to -4)
# Reverse a substring
print(text[-1:-4:-1]) # Output: 'noh' (characters -1 to -3 in
reverse)
a. Extracting Substrings
text = "abcdefgh"
substring = text[2:5] # Output: 'cde' (indices 2, 3, 4)
b. Reversing a String
text = "Python"
reversed_text = text[::-1] # Output: 'nohtyP'
c. Skipping Characters
text = "abcdefgh"
skipped = text[::3] # Output: 'adg' (every 3rd character)
text = "Hello"
without_first = text[1:] # Output: 'ello'
without_last = text[:-1] # Output: 'Hell'
e. Palindrome Check
text = "madam"
is_palindrome = text == text[::-1] # Output: True
7. Handling Errors
Out-of-range indices: Python gracefully handles out-of-range slicing.
text = "Hello"
print(text[0:100]) # Output: 'Hello' (no IndexError)
Empty result: If start is greater than stop, or step conflicts, the result is an empty string.
text = "Hello"
print(text[5:3]) # Output: ''
Slicing is powerful for substring extraction, reversing, and processing strings efficiently.
In Python, you can repeat a string multiple times using the * operator. This is a quick and
efficient way to create a repeated sequence of characters.
Syntax
repeated_string = string * n
1. Basic Repetition
text = "Hello"
repeated_text = text * 3
print(repeated_text) # Output: "HelloHelloHello"
text = "Hello"
repeated_with_spaces = (text + " ") * 3
print(repeated_with_spaces) # Output: "Hello Hello Hello "
3. Using Variables
text = "Python"
times = 4
result = text * times
print(result) # Output: "PythonPythonPythonPython"
6. Concatenation of Strings
String Concatenation in Python is the process of joining two or more strings together. This can
be done using the + operator, or other methods like join() or formatted strings for more
complex scenarios.
The + operator is the simplest and most common way to concatenate strings.
# Basic concatenation
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result) # Output: "Hello World"
greeting = "Hello"
greeting += ", World!"
print(greeting) # Output: "Hello, World!"
3. Using the join() Method
The join() method concatenates elements of a sequence (e.g., list or tuple) into a single string.
name = "Alice"
age = 25
result = f"My name is {name} and I am {age} years old."
print(result) # Output: "My name is Alice and I am 25 years
old."
5. Using format()
name = "Alice"
result = "Hello, {}!".format(name)
print(result) # Output: "Hello, Alice!"
6. Using % Operator
name = "Alice"
result = "Hello, %s!" % name
print(result) # Output: "Hello, Alice!"
Limitations
Using + repeatedly in loops can be inefficient; prefer join() for large concatenations.
# Inefficient:
result = ""
for word in words:
result += word # Creates a new string each time
# Efficient:
result = "".join(words)
7. Checking Membership
Syntax
Examples
2. Case Sensitivity
You can use in to iterate over a string or check membership within loops.
text = "apple"
for char in "aeiou":
if char in text:
print(f"'{char}' is in the word '{text}'.")
Output:
allowed_chars = "0123456789"
user_input = "4567A"
if all(char in allowed_chars for char in user_input):
print("Input is valid.")
else:
print("Invalid input.")
# Output: "Invalid input."
a. Substring Search
email = "[email protected]"
if "@" in email:
print("Valid email address.")
# Output: "Valid email address."
b. Avoid Specific Words
Performance Considerations
Membership checks are efficient because Python internally optimizes string searching. For large
texts, in performs well for simple cases but may become slower for complex patterns. In such
cases, consider regular expressions (re module) for advanced searches.
import re
text = "Python programming is fun"
pattern = "Python"
# Check membership using regex
if re.search(pattern, text):
print("Pattern found!"
8. Comparing Strings
In Python, comparing strings involves checking their equality, inequality, or relative order
(lexicographically). Python provides several operators for comparing strings based on their
content or ordering.
Comparison Operators
Operator Description
1. Checking Equality
str1 = "hello"
str2 = "world"
str3 = "hello"
print(str1 == str2) # Output: False
print(str1 == str3) # Output: True
2. Checking Inequality
str1 = "Python"
str2 = "python"
print(str1 != str2) # Output: True
3. Lexicographical Comparisons
Lexicographical order compares strings based on the order of characters in the Unicode table.
Examples:
4. Case Sensitivity
Examples:
To perform case-insensitive comparisons, you can use string methods like .lower() or
.upper().
Examples:
str1 = "Python"
str2 = "python"
# Case-insensitive comparison
print(str1.lower() == str2.lower()) # Output: True
6. Sorting Strings
Example:
import locale
locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")
result = locale.strcoll("apple", "banana")
print(result) # Output: -1 (negative means "apple" < "banana")
import re
if re.match(r"^hello", "hello world"):
print("String starts with 'hello'")
# Output: String starts with 'hello'
str1 = "listen"
str2 = "silent"
print(sorted(str1) == sorted(str2)) # Output: True
str1 = "short"
str2 = "longer"
print(len(str1) < len(str2)) # Output: True
Conclusion
String comparisons in Python are versatile and can handle everything from simple equality
checks to advanced lexicographical ordering.
Removing spaces from a string in Python can be done in various ways, depending on whether
you want to remove all spaces, leading/trailing spaces, or just specific spaces. Below are
common methods for removing spaces:
Use the strip() method to remove spaces at the beginning and end of the string.
Use the lstrip() method to remove spaces only at the beginning of the string.
Use the rstrip() method to remove spaces only at the end of the string.
Use the replace() method to remove all spaces in the string, including spaces in the middle.
Use "".join() with split() to remove all kinds of whitespace, including tabs and
newlines.
import re
text_list = [" Hello ", " World ", " Python "]
result = [s.strip() for s in text_list]
print(result) # Output: ['Hello', 'World', 'Python']
Comparison of Methods
Method Use Case
Finding substrings in Python refers to locating the presence and position of a smaller string
(substring) within a larger string. Python provides several ways to achieve this, including built-in
string methods and regular expressions.
The find() method returns the index of the first occurrence of the substring. If the substring
is not found, it returns -1.
Syntax:
Example:
text = "Python programming is fun"
index = text.find("programming")
print(index) # Output: 7
The index() method works like find() but raises a ValueError if the substring is not
found.
Example:
Example:
The count() method returns the number of occurrences of a substring in the string.
Example:
For advanced substring searches, including pattern matching, use the re module.
Example:
import re
text = "Python programming is fun"
if re.search(r"programming", text):
print("Substring found")
else:
print("Substring not found")
# Output: Substring found
if substring in text:
highlighted = text.replace(substring, f"[{substring}]")
print(highlighted)
# Output: "Python [programming] is fun"
Comparison of Methods
In Python, you can count the occurrences of a substring within a string using a few different
methods. The most common and straightforward approach is to use the count() method, but
there are other ways as well, depending on your needs.
The count() method is the most direct way to count occurrences of a substring in a string. It
returns the number of non-overlapping occurrences of the substring.
Syntax:
Example:
For more advanced counting, such as counting overlapping substrings or matching patterns, you
can use the re module.
import re
import re
You can manually count the occurrences of a substring by looping through the string and
checking for the substring.
Example:
print(count) # Output: 2
You can split the string by the substring and count the number of resulting parts, which indirectly
gives you the count of the substring occurrences.
Example:
You can use the find() method in a loop to count substrings, especially when you want to
check for substrings that may overlap.
Example:
print(count) # Output: 3
Comparison of Methods
Conclusion
For most cases, the count() method is the easiest and most efficient way to count substrings.
However, if you need more control or need to count overlapping substrings, regular expressions
or a custom loop with find() will be helpful.
12. Strings are Immutable
In Python, strings are immutable, which means once a string is created, it cannot be modified.
If you attempt to change a character or slice a string directly, Python will create a new string
instead. This behavior is different from mutable types like lists, where you can modify their
contents directly.
● Any operation that appears to modify a string, such as changing a character, will actually
result in the creation of a new string.
● You cannot modify the string in place (for example, you cannot change a specific
character within the string by assigning it a new value).
Although you can't modify a string in place, you can reassign a new string to the variable. For
example:
String methods like replace(), upper(), and lower() do not modify the original string,
but instead return a new string:
If you need to perform frequent modifications to a sequence of characters, consider using a list
of characters or a StringIO object (for efficient string building), which are mutable.
Summary
In Python, you can replace one substring with another in a string using the built-in
replace() method. Since strings are immutable, this method returns a new string with the
replacements made, leaving the original string unchanged.
Examples
You can specify the count parameter to limit how many times the replacement occurs.
If the substring you want to replace doesn't exist, the string remains unchanged.
You can replace multiple substrings in a string by calling replace() multiple times.
For more complex replacement patterns (such as replacing based on patterns rather than fixed
substrings), you can use the re.sub() method from the re module.
import re
Key Points
In Python, splitting and joining strings are common operations, often used for processing or
formatting data. Here's an overview of both operations:
1. Splitting Strings
The split() method is used to break a string into a list of substrings based on a specified
separator. By default, it splits based on whitespace (spaces, tabs, newlines), but you can specify
any separator.
Syntax of split()
string.split(separator, maxsplit)
Examples:
text = "apple,orange,banana,grapes"
fruits = text.split(",")
print(fruits)
# Output: ['apple', 'orange', 'banana', 'grapes']
text = "apple,orange,banana,grapes"
fruits = text.split(",", 2) # Split only at the first 2 commas
print(fruits)
# Output: ['apple', 'orange', 'banana,grapes']
In this case, the string is split at only the first two commas, leaving the rest of the string intact.
If you need to split by multiple delimiters, you can use the re.split() method from the re
module.
import re
text = "apple;orange,banana-grapes"
fruits = re.split('[,;-]', text) # Split by comma, semicolon,
or hyphen
print(fruits)
# Output: ['apple', 'orange', 'banana', 'grapes']
2. Joining Strings
The join() method is used to concatenate (join) a list of strings into a single string, with a
specified separator between each element.
Syntax of join()
separator.join(iterable)
● separator: The string that will be placed between each element of the iterable (usually a
list or tuple).
● iterable: A list or tuple containing the strings to be joined.
Examples:
This joins the list of fruit names using a comma followed by a space.
In this case, the words are concatenated without any space or separator.
numbers = range(1, 6)
numbers_str = ", ".join(map(str, numbers)) # Convert numbers to
strings
print(numbers_str)
# Output: "1, 2, 3, 4, 5"
The map(str, numbers) converts the numbers to strings, which are then joined with a
comma and space.
Key Points
● split(): Breaks a string into a list of substrings based on a separator. It is useful for
tokenizing text.
● join(): Combines a list (or any iterable) of strings into one string with a separator. It is
useful for formatting output or creating CSV-like structures.
● Immutability of Strings: Both split() and join() do not modify the original
string. They return new strings.
Summary Example:
# Split a string
text = "apple,orange,banana,grapes"
fruits = text.split(",")
print(fruits) # Output: ['apple', 'orange', 'banana', 'grapes']
In Python, you can change the case of a string using a variety of built-in methods. These
methods allow you to convert all characters to uppercase, lowercase, or capitalize specific letters.
1. Converting to Uppercase
Syntax:
string.upper()
Example:
2. Converting to Lowercase
Syntax:
string.lower()
Example:
The capitalize() method capitalizes the first character of the string and converts the rest to
lowercase.
Syntax:
string.capitalize()
Example:
The title() method capitalizes the first letter of each word in the string.
Syntax:
string.title()
Example:
The swapcase() method swaps the case of all characters in the string (converts uppercase to
lowercase and vice versa).
Syntax:
string.swapcase()
Example:
You can also check if all characters are uppercase, lowercase, or if the string is title-cased.
Methods:
Examples:
text = "HELLO"
print(text.isupper()) # Output: True
print(text.islower()) # Output: False
text2 = "Hello"
print(text2.istitle()) # Output: True
Summary:
The endswith() method checks if the string ends with the specified substring. It returns
True if the string ends with that substring, otherwise False.
Syntax:
Example:
You can also specify a range to check if the substring appears at the end within the specified
range.
If you need case-insensitive checks, you can convert the string to a specific case using lower()
or upper() before using startswith() or endswith().
Example:
result = text.lower().endswith("world!")
print(result)
# Output: True
Summary
In Python, string testing methods are used to check certain properties of a string. These methods
return a boolean value (True or False) based on whether the string meets specific conditions.
Here is a list of the most commonly used string testing methods:
1. isalnum()
Returns True if all characters in the string are alphanumeric (letters and numbers) and there is at
least one character, otherwise False.
Example:
text = "Hello123"
print(text.isalnum()) # Output: True
2. isalpha()
Returns True if all characters in the string are alphabetic (letters only) and there is at least one
character, otherwise False.
Example:
text = "Hello"
print(text.isalpha()) # Output: True
text2 = "Hello123"
print(text2.isalpha()) # Output: False (because of the numbers)
3. isdigit()
Returns True if all characters in the string are digits (0-9), and there is at least one character,
otherwise False.
Example:
text = "12345"
print(text.isdigit()) # Output: True
text2 = "12a45"
print(text2.isdigit()) # Output: False
4. islower()
Returns True if all characters in the string are lowercase letters and there is at least one
character, otherwise False.
Example:
text = "hello"
print(text.islower()) # Output: True
text2 = "Hello"
print(text2.islower()) # Output: False
5. isupper()
Returns True if all characters in the string are uppercase letters and there is at least one
character, otherwise False.
Example:
text = "HELLO"
print(text.isupper()) # Output: True
text2 = "Hello"
print(text2.isupper()) # Output: False
6. isspace()
Returns True if all characters in the string are whitespace (spaces, tabs, newlines), and there is
at least one character, otherwise False.
Example:
7. istitle()
Returns True if the string is in title case (each word's first letter is capitalized and all other
letters are lowercase), otherwise False.
Example:
Returns True if all characters in the string are numeric (can be part of a number, such as digits
or other numeric symbols), and there is at least one character, otherwise False.
Example:
text = "12345"
print(text.isnumeric()) # Output: True
text2 = "12.34"
print(text2.isnumeric()) # Output: False (because of the
decimal point)
9. isdecimal()
Returns True if all characters in the string are decimal characters (digits 0-9), otherwise False.
This is more strict than isnumeric() because it doesn't allow for non-digit characters like
fractions or other numeric symbols.
Example:
text = "12345"
print(text.isdecimal()) # Output: True
text2 = "12.34"
print(text2.isdecimal()) # Output: False
10. isidentifier()
Returns True if the string is a valid Python identifier (i.e., it starts with a letter or underscore,
followed by letters, digits, or underscores), otherwise False.
Example:
text = "my_variable"
print(text.isidentifier()) # Output: True
text2 = "2variable"
print(text2.isidentifier()) # Output: False
11. isnumeric()
Returns True if all characters in the string are numeric characters, and there is at least one
character, otherwise False.
Example:
text = "1234"
print(text.isnumeric()) # Output: True
text2 = "123a"
print(text2.isnumeric()) # Output: False
These methods are useful for validating input and checking the characteristics of strings.
In Python, string formatting allows you to embed variables or expressions inside a string,
providing a way to create dynamic text. There are several ways to format strings in Python,
including using f-strings, str.format(), and the % operator.
Introduced in Python 3.6, f-strings are the most modern and preferred method for string
formatting. An f-string is a string prefixed with f, and you can embed expressions inside curly
braces {}.
Syntax:
f"string {expression}"
Example:
name = "John"
age = 30
formatted_string = f"Hello, my name is {name} and I am {age}
years old."
print(formatted_string)
# Output: "Hello, my name is John and I am 30 years old."
You can also perform operations or call functions inside the curly braces:
pi = 3.14159
formatted_pi = f"Pi is approximately {pi:.2f}."
print(formatted_pi)
# Output: "Pi is approximately 3.14."
The str.format() method is another common way to format strings. You insert placeholders
in the string with curly braces {}, and then pass values to format().
Syntax:
"string {}".format(value)
Example:
name = "John"
age = 30
formatted_string = "Hello, my name is {} and I am {} years
old.".format(name, age)
print(formatted_string)
# Output: "Hello, my name is John and I am 30 years old."
The % operator is an older method of string formatting, and although it's still supported, it's not as
flexible or preferred as f-strings or str.format(). It works similarly to C-style formatting.
Syntax:
"string % (value)"
Example:
name = "John"
age = 30
formatted_string = "Hello, my name is %s and I am %d years old."
% (name, age)
print(formatted_string)
# Output: "Hello, my name is John and I am 30 years old."
In the % operator:
You can specify the alignment and width of the formatted string using f-strings,
str.format(), or the % operator.
Using f-strings:
Using str.format():
Using % operator:
You can pad numbers with leading zeroes in all three formatting methods.
Using f-strings:
number = 5
formatted = f"{number:03}"
print(formatted) # Output: "005"
Using str.format():
number = 5
formatted = "{:03}".format(number)
print(formatted) # Output: "005"
Using % operator:
number = 5
formatted = "%03d" % number
print(formatted) # Output: "005"
You can format numbers to a specific number of decimal places in all three formatting methods.
Using f-strings:
pi = 3.14159
formatted = f"{pi:.2f}"
print(formatted) # Output: "3.14"
Using str.format():
pi = 3.14159
formatted = "{:.2f}".format(pi)
print(formatted) # Output: "3.14"
Using % operator:
pi = 3.14159
formatted = "%.2f" % pi
print(formatted) # Output: "3.14"
Summary
● f-strings: The most modern and preferred method for string formatting (Python 3.6+).
● str.format(): A versatile method for formatting, supporting positional and named
arguments.
● % operator: An older method, still in use for simple formatting but less flexible than the
other two.
For most new projects, f-strings are the recommended approach due to their simplicity,
performance, and readability.
19. Working with Characters
In Python, a character is simply a string of length 1. Python doesn't have a specific "character"
type, as it treats characters as strings with a length of 1. However, you can manipulate and work
with individual characters just like you would with any other string. Below are some operations
you can perform when working with characters in Python:
You can access individual characters in a string by using indexing. The index starts from 0 for
the first character.
Example:
text = "Hello"
first_char = text[0]
print(first_char) # Output: "H"
last_char = text[-1]
print(last_char) # Output: "o"
You can iterate through each character in a string using a loop, such as a for loop.
Example:
text = "Hello"
for char in text:
print(char)
# Output:
# H
# e
# l
# l
# o
You can check whether a character is alphabetic or numeric using the methods isalpha() and
isnumeric().
Example:
char = 'A'
print(char.isalpha()) # Output: True
print(char.isnumeric()) # Output: False
char2 = '1'
print(char2.isalpha()) # Output: False
print(char2.isnumeric()) # Output: True
You can convert characters to uppercase or lowercase using upper() and lower() methods.
Example:
char = "a"
upper_char = char.upper()
print(upper_char) # Output: "A"
char2 = "B"
lower_char = char2.lower()
print(lower_char) # Output: "b"
5. Checking if Character is a Digit or Whitespace
You can use isdigit() to check if a character is a digit, and isspace() to check if it's a
whitespace.
Example:
char = '9'
print(char.isdigit()) # Output: True
6. Comparing Characters
You can compare characters using the comparison operators like ==, <, >, etc. This is based on
their Unicode code points.
Example:
char1 = 'a'
char2 = 'b'
print(char1 == char2) # Output: False
print(char1 < char2) # Output: True (because 'a' comes before
'b' in Unicode)
You can get the ASCII/Unicode value of a character using the ord() function.
Example:
char = 'A'
ascii_value = ord(char)
print(ascii_value) # Output: 65 (ASCII value of 'A')
char2 = 'a'
ascii_value2 = ord(char2)
print(ascii_value2) # Output: 97 (ASCII value of 'a')
You can convert an ASCII value to its corresponding character using the chr() function.
Example:
ascii_value = 65
char = chr(ascii_value)
print(char) # Output: "A"
ascii_value2 = 97
char2 = chr(ascii_value2)
print(char2) # Output: "a"
You can remove non-alphabetic characters from a string (or just check if a character is
alphabetic) using list comprehensions.
Example:
text = "Hello123"
filtered_text = "".join([char for char in text if
char.isalpha()])
print(filtered_text) # Output: "Hello"
10. Working with Character Encodings
Characters in Python are represented using Unicode (UTF-8 by default). You can encode and
decode characters to and from different encodings.
Example:
char = 'A'
encoded_char = char.encode('utf-8')
print(encoded_char) # Output: b'A'
decoded_char = encoded_char.decode('utf-8')
print(decoded_char) # Output: "A"
You can use characters in formatted strings just like other data types.
Example:
char = 'H'
formatted_string = f"The character is {char}"
print(formatted_string) # Output: "The character is H"
You can use the find() method to locate the position of a character within a string.
Example:
text = "Hello"
position = text.find('e')
print(position) # Output: 1 (position of 'e' in the string)
position2 = text.find('x')
print(position2) # Output: -1 (not found)
Summary of Character Operations in Python:
In Python, sorting strings can be done using several methods, depending on the specific
requirements. You can sort the characters in a string, sort a list of strings, or sort based on
specific criteria like case sensitivity or custom rules.
You can use the sorted() function to sort the characters in a string. This function returns a list
of characters, sorted in ascending order. If you need the result to be a string, you can use
"".join() to join the sorted characters back together.
Example:
text = "hello"
sorted_text = "".join(sorted(text))
print(sorted_text) # Output: "ehllo"
● sorted() returns a list of sorted characters.
● join() combines the sorted list of characters back into a string.
If you have a list of strings, you can use the sorted() function to sort the list in alphabetical
order. The list is sorted lexicographically (dictionary order).
Example:
You can sort the strings in descending order by passing the reverse=True argument to the
sorted() function.
Example:
By default, Python sorts strings in a case-sensitive manner, where uppercase letters come before
lowercase letters because of their ASCII values. You can specify how to handle case sensitivity
by using the key argument.
Example:
You can provide a custom sorting function using the key argument. This allows you to sort
strings based on different criteria, such as the length of the strings or their alphabetical order in a
case-insensitive way.
You can use the sort() method to sort the list of strings in place, modifying the original list
directly. This is useful if you don’t need a new sorted list but want to sort the existing one.
Example:
You can also use sort(reverse=True) to sort the list in descending order in place.
Example:
You can also sort strings containing special characters or numbers. The sorted() function will
sort them based on their Unicode code points.
Example:
text = "apple!banana#orange"
sorted_text = "".join(sorted(text))
print(sorted_text) # Output: "!#aabbelnnoopr"
You can use the key parameter with a custom function to define complex sorting criteria. For
example, sorting strings by the number of vowels in them.
def count_vowels(s):
return sum(1 for char in s if char in 'aeiouAEIOU')
words = ["banana", "apple", "orange", "mango"]
sorted_by_vowels = sorted(words, key=count_vowels)
print(sorted_by_vowels) # Output: ['mango', 'banana', 'apple',
'orange']
● sorted(): Returns a sorted list without modifying the original string or list.
● sort(): Sorts a list in place, modifying the original list.
● Reverse sorting: Use reverse=True to sort in descending order.
● Case-sensitive sorting: By default, Python sorts strings case-sensitively.
● Custom sorting: Use key to define custom sorting functions, such as sorting by string
length or case-insensitive sorting.
● In-place sorting: Modify the original list using sort().
In Python, searching in strings can be performed in various ways depending on your needs. You
can search for substrings, find the position of a substring, check if a string contains a specific
character, and more.
1. Using in Keyword
The in keyword is used to check if a substring exists within a string. It returns True if the
substring is found, otherwise False.
Example:
The find() method returns the lowest index where the substring is found in the string. If the
substring is not found, it returns -1.
Example:
not_found_position = text.find("Python")
print(not_found_position) # Output: -1
The index() method is similar to find(), but it raises a ValueError if the substring is not
found, instead of returning -1.
Example:
The count() method returns the number of non-overlapping occurrences of a substring in the
string.
Example:
count_world = text.count("world")
print(count_world) # Output: 1
The startswith() method checks if the string starts with the specified prefix. It returns
True if the string starts with the given substring, otherwise False.
Example:
result2 = text.startswith("world")
print(result2) # Output: False
The endswith() method checks if the string ends with the specified suffix. It returns True if
the string ends with the given substring, otherwise False.
Example:
result2 = text.endswith("Hello")
print(result2) # Output: False
You can also use find() to search for the first occurrence and then continue searching for
subsequent occurrences by adjusting the starting position.
Example:
You can use regular expressions to perform more complex searches, such as pattern matching.
The re module provides several functions like search(), match(), and findall() for
searching.
Example:
import re
The partition() method splits the string at the first occurrence of a separator and returns a
tuple of three parts: the part before the separator, the separator itself, and the part after the
separator. If the separator is not found, it returns the string and two empty strings.
Example:
To find the number of characters and words in a string, you can use various built-in Python
methods. Here's how you can do it:
To count the total number of characters in a string (including spaces, punctuation, etc.), you can
use the len() function.
Example:
To count the number of words in a string, you can split the string by spaces and then count the
number of resulting words. The split() method will handle multiple spaces and split the
string into a list of words.
Example:
● The split() method splits the string by whitespace by default (spaces, tabs, and
newlines).
● It returns a list of words, and len() is used to count the number of words.
If you want to count words using specific delimiters (like commas or periods), you can pass a
separator to the split() method.
Example:
text = "apple,banana,orange,mango"
words = text.split(",") # Split by comma
num_words = len(words)
print(num_words) # Output: 4
4. Counting Non-Empty Words
If the string contains extra spaces or empty words, you can filter out the empty strings before
counting.
Example:
If you want to find how many times a specific word appears in the string, you can use the
count() method.
Example:
You can also use regular expressions to count words, especially when dealing with more
complex cases (like punctuation).
Example:
import re
text = "Hello, world! How are you?"
words = re.findall(r'\b\w+\b', text) # Matches word boundaries
num_words = len(words)
print(num_words) # Output: 5
Summary of Techniques for Counting Characters and Words:
● Counting characters: Use the len() function to count all characters (including spaces
and punctuation).
● Counting words: Use the split() method and count the resulting list length.
● Counting specific words: Use count() to find the number of occurrences of a word.
● Handling multiple spaces: split() handles multiple spaces automatically.
● Using regular expressions: For more advanced cases, re.findall() can match
words using patterns.
In Python, inserting a substring into a string can be done in various ways. Below are a few
methods for inserting a substring into a string:
You can use string slicing to insert a substring at a specific index. This method involves slicing
the original string into two parts and then combining them with the new substring.
Example:
In this example:
● text[:position] takes the part of the string before the insertion point.
● substring is the new string to be inserted.
● text[position:] takes the part of the string after the insertion point.
You can also use the join() method to insert a substring into a string by splitting the string into
a list, inserting the substring, and then joining it back together.
Example:
While the format() method is typically used for formatting strings, you can use it to insert a
substring into a string at a specific position by creating a placeholder.
Example:
If you're using Python 3.6 or later, f-strings provide an elegant way to insert substrings into
strings.
Example:
Here, f-strings are used with slicing to insert the substring at the specified index.
If you want to insert a substring at the first occurrence of a specific substring, you can use the
replace() method. It allows replacing a part of the string, and by controlling it, you can
effectively insert a substring.
Example:
For more complex scenarios, you can use the re.sub() method from the re module to insert a
substring at specific positions.
Example:
import re
In Python, a list is a collection of ordered, mutable elements that can be of any type. Lists are
very versatile and are one of the most commonly used data structures in Python. Here's a
breakdown of how lists work and some key operations:
Creating a List
You can create a list by placing elements inside square brackets [], separated by commas.
Accessing Elements
You can access elements in a list by indexing, with the first element being at index 0. Negative
indices access elements from the end of the list.
# Accessing elements
print(my_list[0]) # Output: 1
print(my_list[-1]) # Output: 3.14
Modifying Elements
Lists are mutable, meaning you can change elements after the list has been created.
# Modifying elements
my_list[1] = 'world'
print(my_list) # Output: [1, 'world', 3, 'hello', 3.14]
Adding Elements
Removing Elements
Slicing Lists
# Slicing a list
sub_list = my_list[1:4] # Elements from index 1 to 3 (4 is not
included)
print(sub_list) # Output: ['new_element', 3.14, 10]
You can check the length of a list with len(), and check if an element is in the list with the in
keyword.
# Length of a list
print(len(my_list)) # Output: 6
# Checking if an element is in the list
print(10 in my_list) # Output: True
print('hello' in my_list) # Output: False
List Comprehensions
List comprehensions provide a concise way to create lists. It can be used to apply an expression
to each element of a sequence.
my_list.reverse()
print(my_list) # Output: ['world', 'new_element', 30, 20, 10,
3.14]
In Python, the range() function can be used to generate a sequence of numbers, which can be
easily converted into a list. The range() function is often used for looping or creating
sequences of numbers. Here's how you can use it to create lists:
# List from 5 to 9
my_list = list(range(5, 10))
print(my_list) # Output: [5, 6, 7, 8, 9]
3. Creating a list with a custom step:
You can combine range() with list comprehensions to generate more complex lists.
Points to Note
● The stop value is exclusive, meaning it will not be included in the list.
● The range() function generates the numbers lazily (it does not create the entire list in
memory at once), but when you use list(range(...)), it converts the sequence
into an actual list.
In Python, lists are mutable, meaning their elements can be updated or modified after the list is
created. You can update elements in a list by accessing them using their index and assigning a
new value. Below are several ways to update the elements of a list:
You can update an element by directly accessing its index and assigning a new value.
# Original list
my_list = [10, 20, 30, 40]
You can update a range of elements using slicing. The left side of the slice specifies the range,
and you can assign a new list of elements.
# Original list
my_list = [10, 20, 30, 40, 50]
# Update the elements from index 1 to index 3 (20, 30, 40) with
new values
my_list[1:4] = [21, 31, 41]
If the list you're assigning has a different length than the slice, Python will automatically adjust
the list.
# Original list
my_list = [10, 20, 30, 40, 50]
You can iterate over the list and update elements based on a condition or any custom logic.
# Original list
my_list = [10, 20, 30, 40, 50]
You can use a list comprehension to modify elements based on a condition or perform
calculations on them.
# Original list
my_list = [10, 20, 30, 40, 50]
You can update elements based on a condition using a loop or list comprehension.
# Original list
my_list = [10, 20, 30, 40, 50]
The enumerate() function can help when you need both the index and value while updating
the list.
# Original list
my_list = [10, 20, 30, 40, 50]
If you have a list of lists (nested list), you can update elements in the inner lists similarly by
accessing the appropriate indices.
You can use the map() function for updating elements in the list based on a function.
# Original list
my_list = [1, 2, 3, 4, 5]
Key Points:
In Python, concatenating two lists means combining them into a single list. There are several
ways to achieve this, including using the + operator, the extend() method, or list unpacking.
The + operator can be used to concatenate two lists. This creates a new list by joining the
elements of both lists.
The extend() method adds all the elements of one list to the end of another list. Unlike the +
operator, this method modifies the first list in place.
Starting from Python 3.5, you can use list unpacking to concatenate lists. This creates a new list
containing all the elements from the two lists.
4. Using itertools.chain()
import itertools
5. Using a Loop
You can concatenate two lists by iterating over one list and appending its elements to another list.
If you are working with lists of strings, you can also use the join() method to concatenate
them into a single string. This is useful when you need a single string output.
Key Differences:
● Using the + operator creates a new list without modifying the original lists.
● The extend() method modifies the first list in place.
● List unpacking offers a concise and elegant syntax for combining lists.
● itertools.chain() is useful when you want an iterator instead of a full list.
● Using loops is less efficient compared to the other methods but is an option in certain
situations.
5. Repetition of Lists
In Python, you can repeat lists using the multiplication (*) operator. This allows you to create a
new list where the original list is repeated a specified number of times.
You can repeat a list a certain number of times by multiplying the list with an integer.
# Define a list
my_list = [1, 2, 3]
When repeating a list containing mutable objects (e.g., lists), all elements will point to the same
object in memory. Be cautious, as modifying one element might affect all repeated elements.
In the example above, all three sublists point to the same list object in memory, so changes to one
sublist affect all of them.
If you need more control over how the list is repeated (e.g., modifying the repeated elements),
you can use a loop.
# Define a list
my_list = [1, 2, 3]
# Define a list
my_list = [1, 2, 3]
● Using the * operator to repeat lists works with both lists containing immutable or
mutable elements, but be careful when using mutable objects because all references will
point to the same memory location.
● When using loops or list comprehensions, you have more control over how elements are
repeated, and this is especially useful for complex manipulations.
6. Membership in Lists
In Python, you can check whether an element is a member of a list using membership operators
such as in and not in. These operators allow you to check if a value exists in the list or if it
does not.
1. Using in Operator
The in operator checks if a specified element is present in the list. It returns True if the element
is found and False if the element is not in the list.
# Define a list
my_list = [10, 20, 30, 40, 50]
The not in operator checks if a specified element is not present in the list. It returns True if
the element is not found and False if the element is in the list.
# Define a list
my_list = [10, 20, 30, 40, 50]
The in operator can also be used to check for membership in a list of strings. It checks if a
specific string exists in the list.
When checking for membership in a nested list, the in operator only checks for membership in
the outermost list. To check for membership in an inner list, you need to access the inner list
explicitly.
# Define a nested list
my_list = [[1, 2], [3, 4], [5, 6]]
You can also check for membership in a list of dictionaries. However, in checks for reference
equality, meaning it checks if a dictionary object exists in the list.
6. Efficiency of in Operator
The time complexity of the in operator depends on the size of the list. For a list of size n, it will
take O(n) time to check for membership because it may need to check each element in the list.
Key Points:
● in checks for the existence of an element in the list and returns True or False.
● not in checks if the element is absent from the list.
● Membership checking works with various data types including integers, strings, and even
more complex data types like lists or dictionaries.
● The membership check can be used with nested lists, but it checks only the outermost list
unless explicitly accessed.
7. Aliasing and Cloning Lists
Python lists are mutable, which means they can be modified after their creation. Understanding
aliasing and cloning is important to avoid unintended modifications and manage list data
effectively.
1. Aliasing
● Definition: Aliasing occurs when two or more variables reference the same list in
memory. Any change made to the list through one alias is reflected in the other aliases
because they share the same memory location.
Example of Aliasing:
# Original list
original_list = [1, 2, 3]
# Create an alias
alias_list = original_list
You can use the is operator to check if two variables are aliases (i.e., reference the same object).
# Check if variables are aliases
print(original_list is alias_list) # Output: True
2. Cloning
● Definition: Cloning creates a copy of the list so that changes made to one list do not
affect the other. Cloning can be done using several methods.
a) Using Slicing
# Original list
original_list = [1, 2, 3]
● Explanation: The slicing operation ([:]) creates a shallow copy of the list, so the two
lists are independent.
# Original list
original_list = [1, 2, 3]
The copy() method (introduced in Python 3.3) creates a shallow copy of the list.
# Original list
original_list = [1, 2, 3]
If the list contains nested lists, the above methods create a shallow copy, meaning only the outer
list is copied. Changes to the nested lists in one list affect the other. For a deep copy, use the
copy module.
import copy
# Original list with nested lists
original_list = [[1, 2], [3, 4]]
● Explanation: A deep copy ensures that nested lists are also copied independently.
Memory Shares the same memory location. Creates a new memory location.
Changes Changes in one alias affect others. Changes in one clone don't affect others.
Use Case Useful for sharing data. Useful for preserving data integrity.
Summary
● Aliasing: Both variables reference the same list, and changes are shared.
● Shallow Cloning: Creates a copy of the list but not the nested objects.
● Deep Cloning: Creates an independent copy of the list, including nested objects.
8. Methods to Process Lists
Python provides a variety of methods to process lists effectively. These methods can be
categorized based on their use, such as adding/removing elements, searching, modifying, and
sorting. Below are some common methods:
1. Adding Elements
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
● extend(): Adds all elements of another iterable (e.g., list, tuple) to the list.
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
my_list = [1, 2, 3]
my_list.insert(1, 99) # Insert 99 at index 1
print(my_list) # Output: [1, 99, 2, 3]
2. Removing Elements
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
● pop(): Removes and returns the element at a specified index. Defaults to the last
element if no index is specified.
my_list = [1, 2, 3]
removed_item = my_list.pop() # Removes last element
print(my_list) # Output: [1, 2]
print(removed_item) # Output: 3
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
my_list = [1, 2, 3, 2]
print(my_list.index(2)) # Output: 1
my_list = [1, 2, 3, 2]
print(my_list.count(2)) # Output: 2
● sort(): Sorts the list in ascending order by default. Use reverse=True for
descending order.
my_list = [3, 1, 4, 1, 5]
my_list.sort()
print(my_list) # Output: [1, 1, 3, 4, 5]
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
5. Copying Lists
my_list = [1, 2, 3]
copied_list = my_list.copy()
print(copied_list) # Output: [1, 2, 3]
6. List Comprehensions
original_list = [1, 2, 3]
doubled_list = [x * 2 for x in original_list]
print(doubled_list) # Output: [2, 4, 6]
original_list = [1, 2, 3, 4]
filtered_list = [x for x in original_list if x > 2]
print(filtered_list) # Output: [3, 4]
my_list = [1, 2, 3]
print(len(my_list)) # Output: 3
● max() and min(): Return the maximum and minimum values in the list.
my_list = [1, 2, 3]
print(max(my_list)) # Output: 3
print(min(my_list)) # Output: 1
● sum(): Returns the sum of all elements in the list (for numeric lists).
my_list = [1, 2, 3]
print(sum(my_list)) # Output: 6
my_list = [0, 1, 2]
print(any(my_list)) # Output: True
print(all(my_list)) # Output: False
Summary Table
Method Functionality
max(), min() Find the largest and smallest elements in the list.
Python provides simple and efficient ways to find the largest (biggest) and smallest elements in a
list. These operations are straightforward with functions like max() and min() or by iterating
through the list.
Example:
You can manually iterate through the list to find the largest and smallest values. This is helpful if
you want to add custom logic during iteration.
Example:
# Initialize variables
largest = my_list[0]
smallest = my_list[0]
Example:
Empty List
Attempting to find the largest or smallest element in an empty list will raise a ValueError.
Handle this case explicitly:
my_list = []
if my_list:
largest = max(my_list)
smallest = min(my_list)
print("Largest:", largest, "Smallest:", smallest)
else:
print("The list is empty.")
Example:
If you need to find the largest or smallest element based on custom criteria, use the key
parameter of the max() and min() functions.
Example:
Summary Table
Method Functionality
The sort() method sorts the list in-place, meaning it modifies the original list.
Syntax:
list.sort(key=None, reverse=False)
Example:
numbers = [5, 2, 9, 1, 5, 6]
# Sort in ascending order
numbers.sort()
print(numbers) # Output: [1, 2, 5, 5, 6, 9]
# Sort in descending order
numbers.sort(reverse=True)
print(numbers) # Output: [9, 6, 5, 5, 2, 1]
The sorted() function returns a new sorted list without modifying the original list.
Syntax:
Example:
numbers = [5, 2, 9, 1, 5, 6]
# Sort in ascending order
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 5, 5, 6, 9]
# Original list remains unchanged
print(numbers) # Output: [5, 2, 9, 1, 5, 6]
# Sort in descending order
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # Output: [9, 6, 5, 5, 2, 1]
The key parameter is used to specify a function to determine the sorting criteria.
You can sort lists of lists or other complex structures by specifying the key parameter.
5. Reversing a List
Example:
numbers = [1, 2, 3, 4]
# Reverse using reverse()
numbers.reverse()
print(numbers) # Output: [4, 3, 2, 1]
# Reverse using slicing
reversed_numbers = numbers[::-1]
print(reversed_numbers) # Output: [1, 2, 3, 4]
numbers = [5, 2, 9, 1, 5, 6]
# Sort in descending order
numbers.sort(reverse=True)
print(numbers) # Output: [9, 6, 5, 5, 2, 1]
8. Edge Cases
Example:
Summary Table
Method Description
In Python, you can count how many times an element occurs in a list using the count()
method or by manually iterating through the list.
The count() method is the simplest and most efficient way to find the number of occurrences
of an element.
Syntax:
list.count(element)
Example:
my_list = [1, 2, 3, 2, 4, 2, 5]
# Count occurrences of 2
occurrences = my_list.count(2)
print("Number of occurrences of 2:", occurrences) # Output: 3
2. Using a Loop
my_list = [1, 2, 3, 2, 4, 2, 5]
element = 2
# Initialize a counter
count = 0
# Iterate through the list
for item in my_list:
if item == element:
count += 1
3. Using collections.Counter
The collections module provides a Counter class, which is helpful for counting
occurrences of all elements in a list.
Example:
You can also get a dictionary of all elements and their counts:
A list comprehension can filter occurrences of the desired element, and the len() function can
count them.
Example:
my_list = [1, 2, 3, 2, 4, 2, 5]
# Count occurrences using list comprehension
occurrences = len([item for item in my_list if item == 2])
print("Number of occurrences of 2:", occurrences) # Output: 3
Example:
my_list = [1, 2, 3, 2, 4, 2, 5]
# Count occurrences using filter
occurrences = len(list(filter(lambda x: x == 2, my_list)))
print("Number of occurrences of 2:", occurrences) # Output: 3
6. Case Sensitivity
For lists containing strings, note that comparisons are case-sensitive. For case-insensitive
counting, convert all elements to lowercase (or uppercase) before counting.
Example:
Example:
my_list = []
# Count occurrences in an empty list
print("Occurrences in empty list:", my_list.count(2)) # Output:
0
# Count an element not in the list
my_list = [1, 2, 3]
print("Occurrences of 5:", my_list.count(5)) # Output: 0
Summary Table
Method Description
filter() with Lambda Function Uses filtering and len() to count occurrences.
Python provides several ways to find the common elements (intersection) between two lists.
Below are the common approaches:
1. Using set.intersection()
The most efficient way to find common elements is by converting the lists to sets and using the
intersection() method.
Example:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Convert lists to sets and find the intersection
common = set(list1).intersection(list2)
print("Common elements:", list(common)) # Output: [4, 5]
Explanation:
You can use a list comprehension to filter out elements that are present in both lists.
Example:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Find common elements using list comprehension
common = [item for item in list1 if item in list2]
print("Common elements:", common) # Output: [4, 5]
Note:
This method works well for smaller lists. For larger lists, it can be less efficient due to repeated
membership checks.
The & operator can be used directly to find the intersection of two sets.
Example:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Convert lists to sets and find intersection using &
common = set(list1) & set(list2)
print("Common elements:", list(common)) # Output: [4, 5]
4. Using filter()
Example:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Find common elements using filter
common = list(filter(lambda x: x in list2, list1))
print("Common elements:", common) # Output: [4, 5]
5. Using collections.Counter (for Duplicate Elements)
If you want to find common elements along with their counts (i.e., accounting for duplicates),
use collections.Counter.
Example:
Explanation:
● Counter & Counter gives the minimum count of each element in both lists.
● elements() converts the result back to a list.
Example:
import numpy as np
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Find common elements using numpy
common = np.intersect1d(list1, list2)
print("Common elements:", common.tolist()) # Output: [4, 5]
Example:
list1 = []
list2 = [1, 2, 3]
# Empty list
print(set(list1).intersection(list2)) # Output: set()
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# No common elements
print(set(list1).intersection(list2)) # Output: set()
Summary Table
Method Description
List Comprehension Simple and Pythonic but less efficient for large
lists.
In Python, lists are highly versatile and can store elements of different data types simultaneously.
This feature makes Python lists a powerful data structure for working with heterogeneous
collections of items.
You can mix strings, integers, floats, booleans, complex numbers, and even other collections like
lists, tuples, and dictionaries in a single list.
Example:
# Accessing elements
print("Integer:", mixed_list[0]) # 42
print("String:", mixed_list[1]) # "Hello"
print("Float:", mixed_list[2]) # 3.14
print("Boolean:", mixed_list[3]) # True
print("Nested List:", mixed_list[4]) # [1, 2, 3]
print("Tuple:", mixed_list[5]) # (4, 5)
print("Dictionary:", mixed_list[6]) # {'key': 'value'}
print("NoneType:", mixed_list[7]) # None
1. Iteration
You can iterate through such a list and perform type-specific operations.
You can add or remove any type of element to/from the list.
# Add elements
mixed_list.append(99.99)
mixed_list.append("New Item")
print("After Adding:", mixed_list)
# Remove elements
mixed_list.remove(True)
print("After Removing:", mixed_list)
3. Type Checking
1. Storing Records
You can store a collection of records, where each record contains various types of information.
2. Heterogeneous Collections
Useful for holding diverse objects such as configuration values, API responses, or test data.
Lists with mixed types are often used to create nested structures for organizing complex data.
data = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30, "skills": ["Python", "Java"]},
{"name": "Charlie", "age": 35, "active": False}
]
print("First Person:", data[0])
print("Second Person's Skills:", data[1]["skills"])
1. Indexing Errors
try:
print(mixed_list[100]) # IndexError
except IndexError as e:
print("Error:", e)
2. Type-Specific Operations
try:
# Trying to add an integer to a string
result = mixed_list[0] + mixed_list[1]
except TypeError as e:
print("Error:", e)
Summary Table
Feature Example
Integer 42
Float 3.14
String "Hello"
None None
Tuple (4, 5)
A nested list is a list that contains other lists as its elements. This structure is useful for
representing complex data, such as matrices, tables, or hierarchical data.
Example:
You can access elements of a nested list using multiple indices, where the first index refers to the
outer list, and the second (or more) refers to the inner list.
Example:
# Accessing a sub-list
print("Second list:", nested_list[1]) # Output: [4, 5, 6]
You can modify any element in a nested list by specifying its indices.
Example:
# Updating an element
nested_list[1][1] = 50
print("Updated Nested List:", nested_list)
# Output: [[1, 2, 3], [4, 50, 6], [7, 8, 9]]
1. Adding a Sub-List
2. Removing Elements
# Removing a sub-list
del nested_list[2]
print("After Removing a Sub-List:", nested_list)
# Output: [[1, 2, 3], [4, 50, 6], [10, 11, 12]]
1. Matrix Representation
# 3x3 matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Edge Cases
2. Irregular Structures
# 2. Update an element
nested_list[0][2] = 99
print("After Update:", nested_list) # Output: [[10, 20, 99],
[40, 50], [60, 70, 80, 90]]
A matrix is a two-dimensional structure represented by rows and columns. In Python, you can
use nested lists to work with matrices. Each sub-list corresponds to a row in the matrix.
Example:
Example:
# Accessing elements
print("Element at Row 1, Column 2:", matrix[0][1]) # Output: 2
print("Element at Row 3, Column 1:", matrix[2][0]) # Output: 7
Matrix Operations
1. Updating Elements
# Removing a row
del matrix[1] # Remove Row 2
print("After Removing Row:")
for row in matrix:
print(row)
# Removing a column
for row in matrix:
del row[1] # Remove Column 2
print("After Removing Column:")
for row in matrix:
print(row)
Matrix Transposition
Example:
# Original matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Matrix Multiplication
Example:
# Two matrices
matrix1 = [
[1, 2],
[3, 4]
]
matrix2 = [
[5, 6],
[7, 8]
]
# Resultant matrix
result = [[0 for _ in range(len(matrix2[0]))] for _ in
range(len(matrix1))]
# Multiplying matrices
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
result[i][j] += matrix1[i][k] * matrix2[k][j]
Flattening a Matrix
To convert a matrix into a single list:
Applications of Matrices
1. Mathematical Computations
○ Linear algebra operations (e.g., transpose, determinant).
2. Data Representation
○ Representing grids (e.g., chessboards, game boards).
3. Image Processing
○ Images can be stored as matrices of pixel values.
# Print Matrix
print("Original Matrix:")
for row in matrix:
print(row)
# Transpose Matrix
transpose = [[row[i] for row in matrix] for i in
range(len(matrix[0]))]
print("Transpose:")
for row in transpose:
print(row)
# Multiply Matrix by 2
scaled_matrix = [[element * 2 for element in row] for row in
matrix]
print("Scaled Matrix:")
for row in scaled_matrix:
print(row)
Matrices using nested lists provide a foundation for many real-world applications.
List comprehensions are a concise and elegant way to create lists in Python. They provide a
shorter syntax to generate lists based on existing sequences or conditions, reducing the need for
verbose loops.
Syntax
1. Creating a List
2. Using Conditions
4. Transforming Strings
5. List of Tuples
# Flattening a 2D list
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in nested_list for item in
sublist]
print(flattened) # Output: [1, 2, 3, 4, 5, 6]
Advanced Examples
1. Conditionals in Expressions
# Conditional expression
numbers = range(10)
parity = ["Even" if x % 2 == 0 else "Odd" for x in numbers]
print(parity) # Output: ['Even', 'Odd', 'Even', 'Odd', ...,
'Odd']
2. Prime Numbers
3. Matrix Transpose
# Transposing a 2D matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in
range(len(matrix[0]))]
print(transpose)
# Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Limitations
Loop Version:
result = []
for x in range(10):
if x % 2 == 0:
result.append(x**2)
print(result) # Output: [0, 4, 16, 36, 64]
Generator Expressions
If you only need to iterate over results without creating a full list, use a generator expression.
Example:
List comprehensions are a powerful tool in Python, enabling concise and efficient data
processing.
17. Tuples
A tuple is a collection data type in Python that is ordered and immutable. Unlike lists, tuples
cannot be modified after creation, making them useful for representing fixed collections of items.
Creating Tuples
Example:
# Creating a tuple
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
You can also create a tuple without parentheses, but this is less common and typically used in
unpacking operations.
Empty Tuple:
# Empty tuple
empty_tuple = ()
print(empty_tuple) # Output: ()
To create a tuple with a single element, you must add a trailing comma.
# Accessing elements
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: 4
Negative indexing allows you to access elements from the end of the tuple.
# Negative indexing
print(my_tuple[-1]) # Output: 5
print(my_tuple[-2]) # Output: 4
Slicing Tuples
# Slicing a tuple
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)
print(my_tuple[:3]) # Output: (1, 2, 3)
print(my_tuple[2:]) # Output: (3, 4, 5)
my_tuple = (1, 2, 3)
# The following will result in a TypeError
# my_tuple[1] = 10
However, you can create a new tuple by concatenating and slicing:
Tuple Operations
1. Concatenation
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4)
2. Repetition
tuple1 = (1, 2)
result = tuple1 * 3
print(result) # Output: (1, 2, 1, 2, 1, 2)
3. Membership
tuple1 = (1, 2, 3, 4)
print(3 in tuple1) # Output: True
print(5 in tuple1) # Output: False
Tuple Unpacking
Tuple unpacking allows you to assign the values of a tuple to individual variables.
# Tuple unpacking
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
x, y = 5, 10
x, y = y, x
print(x, y) # Output: 10 5
Nested Tuples
Tuples can contain other tuples, allowing for the creation of more complex data structures.
# Nested tuple
nested_tuple = ((1, 2), (3, 4), (5, 6))
print(nested_tuple[0]) # Output: (1, 2)
print(nested_tuple[0][1]) # Output: 2
While tuples are immutable and don't have methods for modification, they do have a couple of
useful methods:
my_tuple = (1, 2, 2, 3, 4, 2)
print(my_tuple.count(2)) # Output: 3
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple.index(3)) # Output: 2
Tuple as Keys in Dictionaries
Since tuples are immutable, they can be used as keys in dictionaries, unlike lists which are
mutable.
Applications of Tuples
1. Data Integrity: Tuples are immutable, making them ideal for data that should not
change.
2. Function Return Values: Functions often return multiple values packed into a tuple.
3. Storing Heterogeneous Data: Tuples can hold different data types, which makes them
useful for grouping related but different data.
# Creating a tuple
student = ("Alice", 25, "Computer Science")
# Accessing tuple elements
name, age, course = student
print(f"Name: {name}, Age: {age}, Course: {course}")
# Concatenation and repetition
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4)
# Nested tuple and unpacking
nested_tuple = ((1, 2), (3, 4), (5, 6))
(a, b), (c, d), (e, f) = nested_tuple
print(a, b, c, d, e, f) # Output: 1 2 3 4 5 6
Conclusion
Tuples are a versatile data structure in Python that provide fast access and are immutable,
making them great for storing fixed collections of items. Their immutability makes them useful
in situations where data should not change. Tuples can be used in dictionaries as keys and
support various operations like concatenation, repetition, and unpacking.
A tuple is an ordered collection of elements, and unlike lists, it is immutable, meaning the
elements cannot be changed once the tuple is created.
You can create a tuple without parentheses (also known as tuple packing), though it's less
common and typically used in specific cases like unpacking.
To create a tuple with a single element, you must include a comma after the element. Without
the comma, the value will be treated as a regular value, not a tuple.
4. Empty Tuple
Tuples can store elements of different data types, including integers, strings, and even other
tuples.
6. Nested Tuples
You can create tuples that contain other tuples (nested tuples).
# Nested tuple
nested_tuple = (1, (2, 3), (4, 5))
print(nested_tuple) # Output: (1, (2, 3), (4, 5))
You can create a tuple by passing an iterable (like a list) to the tuple() constructor.
Tuples can also be created from the range() function, which generates a sequence of numbers.
Practical Example:
This tuple contains a string, an integer, another string, and a float, demonstrating that tuples can
hold diverse data types.
Since tuples are ordered collections (indexed), you can access their elements using indices. You
can access individual elements or slices (subsets) of the tuple.
Tuples are indexed starting from 0. You can access elements by providing the index inside square
brackets [].
Example:
2. Negative Indexing
Negative indexing allows you to access elements starting from the end of the tuple. The last
element has an index of -1, the second last is -2, and so on.
Example:
You can access a slice (subset) of the tuple by using a range of indices with the colon : operator.
tuple[start_index:end_index]
Example:
You can also use negative indices in slicing to access elements from the end of the tuple.
Example:
If you have a nested tuple (a tuple within a tuple), you can access elements inside the nested
tuple by chaining indices.
Example:
The index() method can be used to find the index of the first occurrence of an element in the
tuple.
Example:
Practical Example:
# Creating a tuple
my_tuple = ('apple', 'banana', 'cherry', 'date')
# Accessing elements
print(my_tuple[0]) # Output: apple (first element)
print(my_tuple[-1]) # Output: date (last element)
Tuples, being immutable sequences, support a variety of basic operations. These operations are
similar to those for lists but come with the limitation that tuples cannot be modified after
creation.
1. Concatenation of Tuples
You can concatenate two or more tuples using the + operator to combine them into one.
Example:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Concatenating tuples
Example:
tuple1 = (1, 2, 3)
result = tuple1 * 3
3. Membership Test
Example:
my_tuple = (1, 2, 3, 4, 5)
# Checking membership
4. Indexing
You can access individual elements of a tuple using indexing (using []), as described earlier.
Example:
print(my_tuple[1]) # Output: 20
5. Slicing
Tuples support slicing to extract a part of the tuple. The syntax is the same as for lists
([start:end]), where start is inclusive, and end is exclusive.
Example:
Example:
print(len(my_tuple)) # Output: 3
The count() method returns the number of occurrences of an element in the tuple.
Example:
print(my_tuple.count(10)) # Output: 3
The index() method returns the first index of the given element. If the element is not found, it
raises a ValueError.
Example:
print(my_tuple.index(30)) # Output: 2
9. Tuple Unpacking
You can unpack a tuple into individual variables, which allows you to assign each element of the
tuple to a variable.
Example:
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
If you have a nested tuple (a tuple inside another tuple), you can access the inner tuple and
perform operations such as slicing or indexing on the nested elements.
Example:
print(nested_tuple[1][0]) # Output: 2
print(nested_tuple[2][1]) # Output: 5
You can compare two tuples using relational operators (==, !=, >, <, >=, <=). Tuple comparison
is done element by element.
Example:
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 3)
tuple3 = (4, 5, 6)
# Comparing tuples
Example:
my_tuple = (3, 1, 4, 1, 5, 9)
sorted_list = sorted(my_tuple)
sorted_tuple = tuple(sorted_list)
Practical Example:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Concatenation
# Repetition
repeated_result = tuple1 * 2
print("Repeated Tuple:", repeated_result)
# Membership
# Length of a tuple
print("Length:", len(tuple1))
Python provides several built-in functions that can be used to process and manipulate tuples.
Below is an overview of some useful functions you can use to work with tuples:
Example:
Example:
Example:
The sum() function returns the sum of all elements in the tuple. It only works with numeric
elements.
Example:
The sorted() function returns a new sorted list of the elements in the tuple. It doesn't modify
the original tuple because tuples are immutable.
Example:
The tuple() function is used to convert other data types (such as lists) into a tuple.
Example:
my_list = [1, 2, 3, 4]
# Converting list to tuple
tuple_from_list = tuple(my_list)
print(tuple_from_list) # Output: (1, 2, 3, 4)
7. any() - Check if Any Element is True
The any() function checks if any element in the tuple is True. It returns True if at least one
element is truthy; otherwise, it returns False.
Example:
my_tuple = (0, 1, 2)
The all() function checks if all elements in the tuple are True. It returns True if all elements
are truthy, otherwise False.
Example:
my_tuple = (1, 2, 3)
# Check if all elements are True
print(all(my_tuple)) # Output: True (since all elements are
truthy)
The index() function returns the first index of a specified element in the tuple. If the element
is not found, it raises a ValueError.
Example:
The count() function returns the number of occurrences of a specified element in the tuple.
Example:
The reversed() function returns an iterator that produces the elements of the tuple in reverse
order. You can convert the result into a tuple if needed.
Example:
The zip() function can combine two or more tuples (or other iterables) element by element. It
returns an iterator of tuples.
Example:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
# Pairing elements from multiple tuples
zipped = tuple(zip(tuple1, tuple2))
print(zipped) # Output: ((1, 'a'), (2, 'b'), (3, 'c'))
Practical Example of Tuple Functions:
These functions allow you to perform a wide range of operations on tuples, from simple queries
to complex manipulations.
You can create a nested tuple by including tuples as elements inside another tuple.
Example:
Output:
To access elements in a nested tuple, you can use multiple indexing operations, one for each
level of the nested structure.
Example:
You can use loops to iterate through the elements of a nested tuple, either iterating through the
outer tuple and accessing inner tuples, or iterating through the inner tuples as well.
Example:
Output:
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
If you want to access elements inside the inner tuples, you can add another loop:
Output:
1
2
3
4
5
6
7
8
9
You can use nested tuples to represent multi-dimensional data like matrices.
Example:
Concatenation of Nested Tuples: You can concatenate nested tuples just like regular tuples.
Example:
nested_tuple1 = ((1, 2), (3, 4))
nested_tuple2 = ((5, 6), (7, 8))
# Concatenate two nested tuples
concatenated_tuple = nested_tuple1 + nested_tuple2
print(concatenated_tuple)
Output:
((1, 2), (3, 4), (5, 6), (7, 8))
Repetition of Nested Tuples: You can repeat nested tuples just like normal tuples.
Example:
nested_tuple = ((1, 2), (3, 4))
Since tuples are immutable, you cannot modify a tuple directly, but you can modify the inner
lists or tuples by accessing their elements. For example, you can replace an inner tuple with a
new tuple.
Example:
In Python, tuples are immutable, meaning their elements cannot be changed or inserted after the
tuple is created. However, there are ways to simulate the insertion of elements into a tuple by
creating a new tuple with the desired elements.
You can create a new tuple by concatenating an existing tuple with a new element (or another
tuple).
Example:
my_tuple = (1, 2, 3)
# Insert 0 at the beginning
new_tuple = (0,) + my_tuple
print(new_tuple) # Output: (0, 1, 2, 3)
In this example:
Since lists are mutable, you can convert a tuple to a list, modify the list by inserting elements,
and then convert it back to a tuple.
Example:
# Original tuple
my_tuple = (1, 2, 3)
In this example:
You can insert multiple elements in a similar way by using concatenation or by converting to a
list and then inserting a sequence of elements.
Example:
# Original tuple
my_tuple = (1, 2, 3)
# Convert to list
temp_list = list(my_tuple)
Here, we're inserting multiple elements [10, 20] at index 1 by using slicing
(temp_list[1:1] = ...).
Summary:
● Tuples are immutable: You cannot directly insert elements into an existing tuple.
● Concatenation: You can create new tuples by concatenating the original tuple with new
elements or another tuple.
● Convert to list: To insert elements, convert the tuple to a list, modify it, and convert it
back to a tuple.
In Python, tuples are immutable, meaning their elements cannot be modified once the tuple is
created. However, there are workarounds that allow you to simulate the modification of tuple
elements. Here are some strategies:
Since tuples are immutable, you can create a new tuple based on the original tuple with the
desired modifications.
# Original tuple
my_tuple = (1, 2, 3)
If you need to modify multiple elements in a tuple, you can convert the tuple to a list (which is
mutable), make the changes, and then convert it back to a tuple.
# Original tuple
my_tuple = (1, 2, 3)
Here:
● The tuple is converted to a list with list(my_tuple).
● The element at index 1 (the second element) is modified.
● The list is converted back to a tuple using tuple(temp_list).
If the tuple contains mutable objects, such as lists, you can modify the mutable elements within
those objects. However, the tuple itself (the outer structure) cannot be changed.
Here:
If you need to modify multiple elements, you can similarly rebuild the tuple using slicing or
concatenation.
# Original tuple
my_tuple = (1, 2, 3, 4)
Here, we replace elements at index 1 and 2 by concatenating (10, 20) between the sliced
parts of the original tuple.
In Python, tuples are immutable, meaning you cannot delete elements from a tuple directly.
However, you can simulate the removal of elements by creating a new tuple that excludes the
element you want to delete. Here are a few strategies for "deleting" elements from a tuple:
You can create a new tuple by concatenating slices of the original tuple that exclude the element
you want to remove.
Example: Deleting an Element by Rebuilding the Tuple
Suppose you want to delete the second element (index 1) from a tuple.
# Original tuple
my_tuple = (1, 2, 3, 4)
In this example:
You can convert the tuple to a list, modify the list (since lists are mutable), delete the element,
and then convert it back to a tuple.
# Original tuple
my_tuple = (1, 2, 3, 4)
# Convert the tuple to a list
temp_list = list(my_tuple)
# Delete the second element (index 1)
del temp_list[1]
# Convert the list back to a tuple
new_tuple = tuple(temp_list)
print(new_tuple) # Output: (1, 3, 4)
Here:
If you want to delete a specific element (by value), you can use the remove() method after
converting the tuple to a list.
# Original tuple
my_tuple = (1, 2, 3, 4)
In this example:
● temp_list.remove(2) removes the first occurrence of the value 2.
● The modified list is converted back to a tuple.
You can also use list comprehension to create a new tuple excluding specific elements based on a
condition.
# Original tuple
my_tuple = (1, 2, 3, 4)
In this example:
● A new tuple is created by including all elements from the original tuple except those that
are equal to 2.
Summary:
● Tuples are immutable: You cannot delete elements directly from a tuple.
● Rebuild the Tuple: You can create a new tuple by concatenating slices that exclude the
element to be deleted.
● Convert to List: You can convert the tuple to a list, use the del statement or
remove() to delete the element, and then convert it back to a tuple.
● List Comprehension: A clean approach using list comprehension to exclude elements
based on a condition.
26. List Comprehensions-
a) Discussing List Comprehension
List comprehension is a concise and efficient way to create lists in Python. It allows you to
generate a new list by applying an expression to each element in an existing iterable (like a list,
tuple, or range). List comprehensions can be used to transform, filter, or manipulate the elements
of the original iterable in a more compact and readable manner.
This creates a new list by evaluating the expression for each item in the iterable.
Here, the expression x**2 computes the square of each value from the iterable range(5),
resulting in the list [0, 1, 4, 9, 16].
In this example:
● The condition if x % 2 == 0 filters only even numbers, so the list contains [0, 2,
4, 6, 8].
You can combine both an expression and a condition in a single list comprehension.
Here:
● The expression x**2 computes the square of each even number in the range from 0 to 9.
● The if x % 2 == 0 condition filters out only even numbers.
List comprehensions can also be nested to work with multi-dimensional structures like matrices
or lists of lists.
In this example:
● The outer loop iterates over the rows of the matrix (for row in matrix), and the
inner loop iterates over the elements in each row (for element in row).
1. Concise Syntax: List comprehensions reduce the amount of code needed to generate
lists.
2. Readability: They are often easier to read than equivalent for loops, especially for
simple operations.
3. Performance: List comprehensions are usually faster than using loops, as they are
optimized for performance in Python.
Here:
● The condition x % 2 == 0 and x > 5 ensures that only even numbers greater than
5 are considered.
In this example:
List comprehensions provide a concise and readable way to create or transform lists in Python.
List comprehension in Python significantly simplifies tasks that involve creating or transforming
lists by condensing multiple lines of code into a single, compact line. It reduces the need for
writing explicit loops and conditionals, thus making the code more readable and concise. Here's
how tasks are simplified using list comprehension:
1. Concise Code
In a traditional for loop, you need to initialize an empty list, iterate over the items, apply an
expression, and then append the results to the list. List comprehension combines all these steps
into a single expression.
# List comprehension
squares = [x ** 2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Simplification: The code is shortened from four lines to one, making it cleaner and easier to
read.
2. Reducing Redundancy
Without list comprehension, you often need to handle conditions, loops, and modifications
separately. With list comprehension, everything is handled in one place.
Simplification: The filtering logic is neatly packed into the list comprehension, eliminating the
need for multiple lines of code.
List comprehensions allow you to apply transformations (like squaring numbers, converting
strings, etc.) and filtering conditions in one place, making complex tasks more manageable.
Nested loops can be difficult to manage, especially when working with multi-dimensional
structures like matrices. List comprehension allows you to flatten or process multi-dimensional
lists in a much cleaner manner.
Simplification: The nested loops are condensed into a single, easy-to-understand line.
5. Enhanced Readability
List comprehensions improve code readability by making it clear that the task is about creating
or transforming a list. The syntax is compact, and all the logic related to creating the list is
written in one place, improving maintainability.
Simplification: The logic for checking if a character is alphabetic and converting it to uppercase
is condensed into one expression.
List comprehension supports multiple conditions and complex transformations, making it ideal
for cases where you need to apply several conditions or transformations at once.
Simplification: Multiple conditions and transformations are expressed clearly in one line,
making the code compact and readable.
List comprehensions allow you to perform complex list manipulations in a more concise and
efficient way compared to traditional methods.
Here are some practical examples to help you better understand list comprehensions and how
they can simplify tasks.
1. Create a List of Squares
Explanation: The expression x**2 is applied to each number x in the range from 0 to 9,
creating a list of their squares.
Goal: Extract all alphabetic characters from a string and convert them to uppercase.
Explanation: This list comprehension first filters for even numbers (x % 2 == 0), then
computes their squares (x**2).
Explanation: The first two numbers are predefined, and each subsequent number is the sum of
the last two numbers in the sequence, generated using list comprehension.
Goal: Separate the even and odd numbers from a list into two different lists.
Explanation: The list comprehension is used twice: one to filter even numbers and another to
filter odd numbers from the list.
8. Nested List Comprehension with Multiple Conditions
Goal: Create a list of squares of even numbers that are greater than 5.
Explanation: This combines multiple conditions (x % 2 == 0 and x > 5) to filter the even
numbers that are greater than 5, and then computes their squares (x**2).
Explanation: The ord(char) function is used to get the ASCII value of each character in the
list.
Explanation: The list comprehension constructs key-value pairs by pairing each key with its
corresponding value from the other list.
Summary of Examples
These examples should help you understand how list comprehensions work and simplify
common tasks in Python.
d) Split( )
The split() method is commonly used to break a string into a list of substrings based on a
delimiter, such as spaces, commas, or other characters. You can combine the split() method
with list comprehensions to process strings more efficiently.
# Sentence
sentence = "This is a list comprehension example"
Explanation:
● The split() method splits the sentence into words by spaces (default delimiter).
● The list comprehension iterates over each word returned by split() and stores them in
the words list.
Goal: Split a sentence into words and convert each word to uppercase.
# Sentence
sentence = "This is a list comprehension example"
# Split the sentence into words and convert each to uppercase
uppercase_words = [word.upper() for word in sentence.split()]
print(uppercase_words) # Output: ['THIS', 'IS', 'A', 'LIST',
'COMPREHENSION', 'EXAMPLE']
Explanation:
# Comma-separated string
csv_string = "apple,banana,orange,grape"
# Split the string into individual items
items = [item for item in csv_string.split(',')]
print(items) # Output: ['apple', 'banana', 'orange', 'grape']
Explanation:
Goal: Split a sentence into words, then filter out words with fewer than 4 characters.
# Sentence
sentence = "This is an example of list comprehension"
# Split the sentence into words and filter those with length >=
4
long_words = [word for word in sentence.split() if len(word) >=
4]
print(long_words) # Output: ['This', 'example', 'list',
'comprehension']
Explanation:
Goal: Split a string of numbers and convert each part into an integer.
# String of numbers
numbers = "10 20 30 40 50"
Explanation:
Goal: Split each sentence in a list into words and store the words in separate lists.
# List of sentences
sentences = ["This is a sentence", "Python is fun", "List
comprehension is powerful"]
Explanation:
● The outer list comprehension iterates over each sentence in the sentences list.
● The split() method splits each sentence into words.
Summary
● split() is often used in list comprehensions to break strings into parts based on a
delimiter.
● With Conditions: You can filter the results of the split using conditions (e.g., word
length).
● Transformation: You can apply transformations like changing case or converting strings
to integers in the list comprehension.
List comprehensions, combined with split(), offer a clean, concise way to process strings
and generate lists based on those strings.
27. Tuple comprehensions-
a)DiscussingTuple Comprehensions
In Python, tuple comprehensions do not exist in the same way as list comprehensions.
However, you can use generator expressions to achieve similar functionality. A generator
expression works like a tuple comprehension but returns a generator object, which can be
converted into a tuple if necessary.
The syntax for a generator expression is similar to that of a list comprehension but uses round
parentheses () instead of square brackets [].
Explanation:
● The expression x**2 for x in range(5) is a generator expression that generates
the squares of numbers from 0 to 4.
● Wrapping it in the tuple() function converts the generator into a tuple.
Explanation:
Goal: Create a tuple of squares for numbers that are both even and greater than 3.
Explanation:
● The condition x % 2 == 0 and x > 3 ensures only even numbers greater than 3
are selected.
● The result is squared, and then the generator expression is wrapped in the tuple()
function to create a tuple.
# List of strings
words = ["apple", "banana", "cherry"]
# Use a generator expression to create a tuple of lengths of the
words
word_lengths = tuple(len(word) for word in words)
print(word_lengths) # Output: (5, 6, 6)
Explanation:
● The generator expression len(word) for word in words calculates the length
of each word in the words list.
● The result is a tuple of word lengths.
Goal: Create a tuple of tuples, where each inner tuple contains the number and its square.
● The generator expression creates a tuple for each number x, with the number and its
square as the elements of the inner tuple.
● The outer tuple() wraps the generator to convert it into a tuple of tuples.
1. No Direct Syntax for Tuple Comprehensions: Python doesn't have a specific syntax for
tuple comprehensions. Instead, generator expressions are used inside the tuple()
function to create a tuple.
2. Efficient Memory Usage: Generator expressions are memory-efficient since they
generate values one by one, rather than storing them in memory all at once as a list does.
This makes them a better choice when dealing with large datasets.
3. Readable and Concise: Using generator expressions inside tuple() provides a
compact and readable way to generate tuples from existing data.
Memory Stores all elements in memory Generates items one at a time, more memory
efficient
Summary
● Tuple comprehension does not exist as a standalone feature, but you can create a tuple
using generator expressions inside the tuple() function.
● They work similarly to list comprehensions, allowing for concise and efficient creation of
tuples based on some transformation or filtering of elements.
b)Tuple Methods
In Python, tuples are immutable, meaning once they are created, their elements cannot be
modified. However, tuples come with a variety of built-in methods that allow you to perform
operations on them, such as counting occurrences of elements, finding their index, and more.
While these methods are available for working with tuples, they are not directly related to tuple
comprehension (which uses generator expressions to generate tuples). However, understanding
how tuple methods can be used alongside tuple comprehension can help you perform common
tasks efficiently.
You can combine tuple comprehension with tuple methods to process or analyze the generated
tuples. Below are examples of how tuple methods can be used in conjunction with tuple
comprehension.
Goal: Create a tuple of numbers and count how many times a specific number appears.
Using count() Method with Tuple Comprehension:
Explanation:
Goal: Create a tuple of names and find the index of a specific name.
Explanation:
● The generator expression creates a tuple of names like "Name0", "Name1", ..., "Name4".
● The index("Name3") method finds the index of "Name3" in the tuple.
Example 3: Getting the Length of a Tuple
Explanation:
Goal: Create a tuple of numbers and find the smallest and largest numbers.
Explanation:
● The generator expression creates a tuple of numbers from 0 to 9.
● The min() function finds the smallest element, and max() finds the largest element in
the tuple.
Goal: Create a tuple, count occurrences of elements, and find their index.
Explanation:
Summary
While tuple comprehension does not exist directly in Python, you can simulate it using
generator expressions inside the tuple() function. Once the tuple is created, you can use
various tuple methods like count(), index(), len(), min(), and max() to process the
tuple and extract useful information. These methods can be very useful in tuple comprehension,
especially when you need to count, search, or analyze data.
c) Index Method
The index() method is a built-in method for tuples in Python that returns the index (position)
of the first occurrence of a specified element in the tuple. If the element is not found, it raises a
ValueError.
When you use tuple comprehension (via a generator expression) to create a tuple, you can
then use the index() method to find the position of an element within the generated tuple.
tuple.index(element)
Goal: Create a tuple of even numbers using tuple comprehension, then find the index of the first
occurrence of a specific number.
Explanation:
Goal: Try to find the index of an element that doesn't exist in the tuple.
Explanation:
Output:
Goal: Create a tuple of numbers and find the index of the first number that satisfies multiple
conditions.
Goal: Create a tuple of tuples and find the index of a specific inner tuple.
Explanation:
● The generator expression creates a tuple of tuples: ((0, 0), (1, 1), (2, 4),
(3, 9), (4, 16)).
● The index((2, 4)) method returns the index of the first occurrence of the tuple (2,
4), which is 2.
● Tuple comprehension (via a generator expression inside tuple()) allows you to create
tuples based on some condition or transformation.
● After creating the tuple, you can use the index() method to find the index of the first
occurrence of a specified element.
● If the element is not found, a ValueError will be raised, so it’s good practice to handle
this using a try-except block.
Tuple comprehension combined with the index() method can be useful for finding positions
of elements in dynamically created tuples.
d) Count Method
The count() method is a built-in method for tuples in Python that returns the number of times
a specified element appears in a tuple. When used with tuple comprehension, it can help you
count the occurrences of a particular element in a dynamically created tuple.
tuple.count(element)
● element: The element whose occurrences you want to count in the tuple.
Here's how you can use the count() method on a tuple created with a generator expression
(which mimics tuple comprehension) to count the occurrences of a specific element.
Goal: Create a tuple of numbers using tuple comprehension, and then count how many times a
specific number appears in the tuple.
Explanation:
Goal: Create a tuple with repeated elements and count how many times a specific element
appears.
Explanation:
Goal: Create a tuple with numbers and count how many times a number divisible by both 2 and
3 appears.
Explanation:
Goal: Create a tuple of tuples and count how many times a specific inner tuple appears.
Explanation:
Explanation:
● The empty tuple () has no elements, so the count(10) method returns 0, indicating
that 10 is not found.
Tuple comprehension with count() is especially useful when you need to generate tuples
on-the-fly based on certain conditions and quickly analyze the frequency of elements within the
generated tuple.
Module 10 - Sets
1. Introduction to set
In Python, a set is an unordered collection of unique elements. It is similar to a list or tuple, but
unlike those data structures, a set does not allow duplicate values. Sets are commonly used when
you need to store multiple items, but order and duplicates don't matter.
● Unordered: The elements in a set do not have a defined order. When you iterate over a
set, the items will not be in the order you added them.
● Unique elements: A set does not allow duplicate items. If you try to add a duplicate item
to a set, it will not be added.
● Mutable: You can add and remove elements from a set after it has been created.
● Iterable: You can loop through the elements of a set.
Creating a Set:
You can create a set using curly braces {} or the set() constructor.
Example:
Operations on Sets:
Example:
my_set = {1, 2, 3, 4}
# Adding an element
my_set.add(5)
print(my_set)
# Removing an element
my_set.remove(3)
print(my_set)
# Set operations
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Union
union_set = set1 | set2
print(union_set)
# Intersection
intersection_set = set1 & set2
print(intersection_set)
# Difference
difference_set = set1 - set2
print(difference_set)
Set Methods:
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Union
print(set_a.union(set_b)) # {1, 2, 3, 4, 5}
# Intersection
print(set_a.intersection(set_b)) # {3}
# Difference
print(set_a.difference(set_b)) # {1, 2}
# Subset check
print(set_a.issubset({1, 2, 3, 4})) # True
Sets are useful when you need to ensure uniqueness and perform operations like unions,
intersections, and differences efficiently.
The internal working of sets in Python is based on the concept of a hash table (also known as a
hash map). Let’s break down how sets are implemented and how they work under the hood:
1. Hashing:
● Each element in a set is hashed using a hash function. A hash function takes an element
(like a number or a string) and produces a fixed-size integer (called the hash value) which
is used to place the element in a specific position within the underlying data structure.
● The hash value determines the location of the element in the hash table.
● This hashing mechanism ensures that lookups, insertions, and deletions are generally
very fast (average time complexity of O(1)).
● Python sets are implemented using a hash table, which is a collection of "buckets" or
"slots".
● When an element is added to the set, its hash value is calculated and used to place the
element into a particular bucket (or slot).
● Each bucket can contain one or more elements (in case of hash collisions, which are rare
but can happen when two elements produce the same hash value).
3. Collisions:
● Hash collisions occur when two different elements have the same hash value.
● Python handles collisions using open addressing (specifically linear probing). In this
method, if two elements have the same hash value, the set will try to place the second
element in the next available slot. If the slot is already taken, it continues checking the
next slot until an empty one is found.
4. Uniqueness:
● Because sets do not allow duplicate elements, when adding a new element to a set,
Python checks if the element already exists in the set by comparing the element’s hash
value.
● If the element is already present (i.e., it is already in a slot in the hash table), the new
element will not be added. This ensures the uniqueness of elements in the set.
5. Time Complexity:
● Insertion: O(1) on average, since the hash function quickly determines where to insert
the element.
● Deletion: O(1) on average, because the hash value is used to directly access the location
of the element.
● Lookup: O(1) on average, as the hash value allows for direct access to the element.
6. Resizing:
● When the number of elements in a set grows beyond a certain threshold, the hash table
needs to be resized (typically doubled) to maintain its efficiency.
● During resizing, the set will be rehashed, and the elements will be redistributed into new
slots according to their hash values.
● Resizing helps in maintaining the O(1) complexity for operations like insertion and
lookup.
7. Efficiency of Operations:
● Membership Test (in): Checking if an element is in a set (e.g., x in my_set) is very
fast because the hash table allows for constant-time lookups.
● Adding an Element: Adding an element also happens in constant time, on average, since
the hash value of the element is used to find its slot in the hash table.
● Removing an Element: Removing an element uses the same hash-based mechanism, so
it is efficient as well.
my_set = {1, 2, 3}
● Python calculates the hash of each element (1, 2, 3) and places them in different buckets
based on these hash values.
● When you check membership (e.g., 3 in my_set), Python calculates the hash of 3
and checks the corresponding bucket directly, ensuring a quick lookup.
● If you try to add 2 again, Python will calculate its hash and find that 2 is already in the
set, thus preventing duplicates.
# Create a set
my_set = {1, 2, 3}
This code shows the hash values of the elements in the set. These hash values are used internally
to determine where each element should be placed within the hash table.
Summary:
● Sets in Python are implemented using hash tables, with each element being hashed to
a specific bucket.
● Uniqueness is ensured by checking whether an element already exists based on its hash
value before adding it.
● Time complexity for most operations (insertion, deletion, and lookup) is O(1) on
average due to the efficient hash table structure.
3. Set in Mathematics
Types of Sets:
1. Finite Set: A set that contains a definite number of elements. For example, A={1,2,3}A
= \{1, 2, 3\}A={1,2,3} is a finite set.
2. Infinite Set: A set that contains an infinite number of elements. For example,
B={1,2,3,… }B = \{1, 2, 3, \dots\}B={1,2,3,…} is an infinite set (the set of all natural
numbers).
3. Empty Set (Null Set): A set that contains no elements. It is denoted as ∅\emptyset∅ or
{}\{\}{}.
4. Singleton Set: A set that contains exactly one element. For example, C={1}C =
\{1\}C={1} is a singleton set.
5. Subset: A set AAA is a subset of set BBB if all elements of AAA are also elements of
BBB. This is denoted as A⊆BA \subseteq BA⊆B. If AAA contains at least one element
that is not in BBB, then AAA is not a subset of BBB.
6. Power Set: The set of all subsets of a given set. For example, if A={1,2}A = \{1,
2\}A={1,2}, the power set of AAA is P(A)={∅,{1},{2},{1,2}}\mathcal{P}(A) =
\{\emptyset, \{1\}, \{2\}, \{1, 2\}\}P(A)={∅,{1},{2},{1,2}}.
7. Universal Set: The set that contains all the elements under consideration, often denoted
by UUU. Any other set is a subset of the universal set.
8. Equal Sets: Two sets AAA and BBB are equal if they contain exactly the same elements.
This is denoted as A=BA = BA=B.
Set Notation:
1. Roster (Tabular) Form: In this form, a set is written by listing all its elements within
curly braces. For example, A={1,2,3}A = \{1, 2, 3\}A={1,2,3} or B={a,b,c}B = \{a, b,
c\}B={a,b,c}.
2. Set-Builder Notation: In this form, a set is described by a rule or property that its
elements satisfy. For example:
○ A={x∣x is a natural number less than 5}={1,2,3,4}A = \{ x \mid x \text{ is a
natural number less than 5} \} = \{1, 2, 3, 4\}A={x∣x is a natural number less
than 5}={1,2,3,4}
○ B={x∣x is an even number}B = \{ x \mid x \text{ is an even number} \}B={x∣x is
an even number}
Operations on Sets:
1. Union (∪\cup∪): The union of two sets AAA and BBB is the set of elements that are in
either AAA, or BBB, or in both.
○ Example: A={1,2},B={2,3}A = \{1, 2\}, B = \{2, 3\}A={1,2},B={2,3}, then
A∪B={1,2,3}A \cup B = \{1, 2, 3\}A∪B={1,2,3}.
2. Intersection (∩\cap∩): The intersection of two sets AAA and BBB is the set of elements
that are in both AAA and BBB.
○ Example: A={1,2},B={2,3}A = \{1, 2\}, B = \{2, 3\}A={1,2},B={2,3}, then
A∩B={2}A \cap B = \{2\}A∩B={2}.
3. Difference (−-−): The difference of two sets AAA and BBB, denoted A−BA - BA−B, is
the set of elements that are in AAA but not in BBB.
○ Example: A={1,2,3},B={2,3,4}A = \{1, 2, 3\}, B = \{2, 3,
4\}A={1,2,3},B={2,3,4}, then A−B={1}A - B = \{1\}A−B={1}.
4. Complement: The complement of a set AAA is the set of all elements in the universal set
UUU that are not in AAA.
○ If U={1,2,3,4,5}U = \{1, 2, 3, 4, 5\}U={1,2,3,4,5} and A={2,4}A = \{2,
4\}A={2,4}, then the complement of AAA, denoted A′A'A′, is A′={1,3,5}A' =
\{1, 3, 5\}A′={1,3,5}.
5. Symmetric Difference (△\triangle△): The symmetric difference of two sets AAA and
BBB is the set of elements that are in either AAA or BBB, but not in both.
○ Example: A={1,2,3},B={3,4,5}A = \{1, 2, 3\}, B = \{3, 4,
5\}A={1,2,3},B={3,4,5}, then A△B={1,2,4,5}A \triangle B = \{1, 2, 4,
5\}A△B={1,2,4,5}.
Venn Diagrams:
Venn diagrams are a visual representation of sets and their relationships. The sets are usually
depicted as circles, and the relationships (union, intersection, etc.) are shown by the areas where
the circles overlap.
Conclusion:
In mathematics, a set is a fundamental concept that deals with collections of objects, and it plays
a central role in various areas of mathematics, including algebra, geometry, and probability. The
operations on sets allow us to combine and compare different sets, making them an essential tool
in mathematical analysis and problem-solving.
In Python, the set data type provides built-in methods for performing set operations like union,
intersection, and difference. These operations are analogous to the mathematical concepts of
union, intersection, and difference. Python sets are implemented with hash tables, so these
operations are efficient.
1. Union (| or .union()):
The union of two sets is a set that contains all the elements from both sets, excluding duplicates.
Example:
Output:
The intersection of two sets is a set that contains only the elements that are present in both sets.
Example:
3. Difference (- or .difference()):
The difference between two sets is a set that contains the elements that are in the first set but not
in the second set.
Example:
Output:
These methods and operators make it easy to perform set operations in Python, and they can be
combined with other set operations to solve more complex problems efficiently.
In addition to union, intersection, and difference, Python's set data type provides several other
useful methods for various set operations. Here’s a list of other common set methods and their
explanations:
1. .add():
Example:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
my_set.add(2) # No change, as 2 is already in the set
print(my_set) # Output: {1, 2, 3, 4}
2. .clear():
Example:
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()
3. .copy():
● Returns a shallow copy of the set. The original set remains unchanged.
Example:
my_set = {1, 2, 3}
copied_set = my_set.copy()
print(copied_set) # Output: {1, 2, 3}
4. .discard():
● Removes an element from the set if it exists. If the element is not present, it does nothing
(unlike .remove() which raises a KeyError if the element is not found).
Example:
my_set = {1, 2, 3}
my_set.discard(2)
print(my_set) # Output: {1, 3}
my_set.discard(4) # No error, as 4 is not in the set
print(my_set) # Output: {1, 3}
5. .remove():
● Removes an element from the set. If the element is not found, it raises a KeyError.
Example:
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
# This will raise a KeyError because 4 is not in the set
my_set.remove(4) # KeyError: 4
6. .pop():
● Removes and returns an arbitrary element from the set. If the set is empty, it raises a
KeyError. The element removed is not predictable, as sets are unordered.
Example:
my_set = {1, 2, 3}
popped_element = my_set.pop()
print(popped_element) # Output could be any element from the
set, e.g., 1
print(my_set) # The remaining set, e.g., {2, 3}
7. .issubset():
● Returns True if the set is a subset of another set (i.e., all elements of the set are
contained in the other set).
Example:
set1 = {1, 2}
set2 = {1, 2, 3}
print(set1.issubset(set2)) # Output: True
print(set2.issubset(set1)) # Output: False
8. .issuperset():
● Returns True if the set is a superset of another set (i.e., the set contains all elements of
the other set).
Example:
set1 = {1, 2, 3}
set2 = {2, 3}
print(set1.issuperset(set2)) # Output: True
print(set2.issuperset(set1)) # Output: False
9. .isdisjoint():
● Returns True if the set has no elements in common with another set (i.e., the intersection
is empty).
Example:
set1 = {1, 2, 3}
set2 = {4, 5, 6}
set3 = {2, 3, 4}
print(set1.isdisjoint(set2)) # Output: True (no common
elements)
print(set1.isdisjoint(set3)) # Output: False (they have common
elements 2 and 3)
10. .intersection_update():
● Updates the set by keeping only the elements that are present in both sets (i.e., the
intersection).
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.intersection_update(set2)
print(set1) # Output: {3, 4}
11. .difference_update():
● Updates the set by removing elements found in another set (i.e., the difference between
the two sets).
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.difference_update(set2)
print(set1) # Output: {1, 2}
12. .symmetric_difference_update():
● Updates the set by keeping only elements that are in either of the sets but not in both (i.e.,
the symmetric difference).
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.symmetric_difference_update(set2)
print(set1) # Output: {1, 2, 5, 6}
● Updates the set by adding elements from another set (or iterable). Duplicates are not
added.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1) # Output: {1, 2, 3, 4, 5}
These methods provide powerful and flexible operations to manage and manipulate sets
efficiently in Python.
6. Set Comprehensions
Set comprehensions in Python allow you to create a new set by applying an expression to each
element in an existing iterable. It provides a concise and readable way to generate sets, similar to
list comprehensions, but with a {} syntax.
Syntax:
Examples:
5. Removing Duplicates:
duplicates = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = {x for x in duplicates}
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
Summary:
Set comprehensions are a powerful and concise way to create sets in Python. You can use them
with or without conditions and even nested loops, providing great flexibility for generating sets
from iterables.
Module 11 - Dictionaries
1. Operations on Dictionaries
In Python, dictionaries are unordered collections of key-value pairs. You can perform a variety of
operations on dictionaries, such as adding, removing, accessing, and modifying elements. Here
are some common operations:
1. Creating a Dictionary
2. Accessing Values
● Add or Update:
4. Removing Elements
● Using del:
● Using pop():
● Using popitem():
● Using clear():
if 'name' in my_dict:
print("Key 'name' exists")
8. Copying a Dictionary
my_dict_copy = my_dict.copy()
9. Merging Dictionaries
● Using update():
Adding Methods:
copy()
This method returns a shallow copy of the dictionary. Changes made to the copied dictionary will
not affect the original one.
original_dict = {'name': 'Alice', 'age': 30}
copied_dict = original_dict.copy()
copied_dict['city'] = 'New York'
print(original_dict) # {'name': 'Alice', 'age': 30}
print(copied_dict) # {'name': 'Alice', 'age': 30, 'city':
'New York'}
update(iterable)
The update() method updates the dictionary with elements from another dictionary or
iterable. If the key exists, its value is updated. If it doesn't, a new key-value pair is added.
original_dict = {'name': 'Alice', 'age': 30}
another_dict = {'age': 31, 'city': 'New York'}
original_dict.update(another_dict)
print(original_dict) # {'name': 'Alice', 'age': 31, 'city':
'New York'}
setdefault(key, default)
This method returns the value of the specified key. If the key doesn't exist, it inserts the key with
a default value and returns the default value.
my_dict = {'name': 'Alice'}
print(my_dict.setdefault('age', 25)) # 25, and adds {'age': 25}
print(my_dict) # {'name': 'Alice', 'age': 25}
fromkeys(sequence, value)
This method creates a new dictionary with keys from the specified sequence and values set to the
specified value. The sequence is usually an iterable (e.g., list, tuple).
keys = ['name', 'age', 'city']
default_value = 'Unknown'
new_dict = dict.fromkeys(keys, default_value)
print(new_dict) # {'name': 'Unknown', 'age': 'Unknown', 'city':
'Unknown'}
Removing Methods:
pop(key, default)
This method removes and returns the value associated with the specified key. If the key does not
exist, it returns the default value if provided (or raises a KeyError if no default is provided).
my_dict = {'name': 'Alice', 'age': 30}
value = my_dict.pop('age')
print(value) # 30
print(my_dict) # {'name': 'Alice'}
# Using default value
value = my_dict.pop('city', 'Not Found')
print(value) # Not Found
popitem()
This method removes and returns an arbitrary (key, value) pair as a tuple. If the dictionary is
empty, it raises a KeyError.
my_dict = {'name': 'Alice', 'age': 30}
item = my_dict.popitem()
print(item) # ('age', 30) or ('name', 'Alice'), depending on
the implementation
print(my_dict) # The remaining key-value pair
clear()
This method removes all items from the dictionary, leaving it empty.
my_dict = {'name': 'Alice', 'age': 30}
my_dict.clear()
print(my_dict) # {}
Example of Adding and Removing Operations:
# Adding elements
my_dict = {'name': 'Alice'}
my_dict.update({'age': 30, 'city': 'New York'})
my_dict.setdefault('country', 'USA')
my_dict_fromkeys = dict.fromkeys(['gender', 'profession'],
'Unknown')
# Removing elements
removed_value = my_dict.pop('age')
print("Removed Value:", removed_value) # 30
print("Dictionary after pop:", my_dict) # {'name': 'Alice',
'city': 'New York', 'country': 'USA'}
item = my_dict.popitem()
print("Removed Item:", item) # ('country', 'USA') or any other
random key-value pair
print("Dictionary after popitem:", my_dict) # {'name': 'Alice',
'city': 'New York'}
my_dict.clear()
print("Dictionary after clear:", my_dict) # {}
By default, a for loop on a dictionary will iterate over the dictionary's keys.
Output:
name
age
city
To iterate over the values of the dictionary, you can use the values() method:
Output:
Alice
30
New York
If you want to access both the key and the value at the same time, you can use the items()
method, which returns a view of the dictionary’s key-value pairs as tuples.
Output:
You can also add conditions to the for loop to perform operations based on certain criteria.
Output:
print(my_dict)
Output:
You can also iterate through nested dictionaries using a for loop:
Output:
person1:
name: Alice
age: 30
person2:
name: Bob
age: 25
Summary:
In Python, you can sort the elements of a dictionary by using sorted() with a lambda
function. By default, dictionaries are unordered collections, but you can sort them based on their
keys or values.
1. Sorting by Keys
To sort the dictionary by its keys, you can use the sorted() function on the dictionary's keys
and create a new sorted dictionary.
# Sorting by keys
sorted_dict_by_key = {key: my_dict[key] for key in
sorted(my_dict, key=lambda x: x)}
print(sorted_dict_by_key)
Output:
Here, sorted(my_dict) sorts the dictionary by its keys, and the lambda x: x simply
returns the key itself for comparison.
2. Sorting by Values
If you want to sort the dictionary by its values, you can pass a lambda function to the key
argument of sorted(). The lambda will return the value for sorting.
# Sorting by values
sorted_dict_by_value = {key: value for key, value in
sorted(my_dict.items(), key=lambda item: item[1])}
print(sorted_dict_by_value)
Output:
In this case, my_dict.items() returns the dictionary as a list of key-value tuples. The
lambda function lambda item: item[1] sorts by the value (the second item in each tuple).
Output:
Output:
Output:
Key Points:
● sorted() returns a list, so to get a sorted dictionary, you need to rebuild it (e.g., using
dictionary comprehension).
● Lambda functions allow you to specify custom sorting logic (e.g., sorting by key, value,
or other criteria).
● reverse=True allows sorting in descending order.
You can convert a list into a dictionary in Python in a variety of ways, depending on how the list
is structured. Here are some common methods:
If you have two lists — one for keys and one for values — you can use the zip() function to
combine them into a dictionary.
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']
Output:
If your list consists of tuples, where each tuple contains a key-value pair, you can directly
convert it to a dictionary using dict().
Output:
If you have a list of elements and you want to generate keys with default values (e.g., None or
another value), you can use list comprehension to create a dictionary.
keys = ['name', 'age', 'city']
# Create a dictionary with default value None for all keys
my_dict = {key: None for key in keys}
print(my_dict)
Output:
You can also use list comprehension to generate keys based on some logic.
Output:
If you have a list of keys and you want to create a dictionary where each key has a specific
default value, you can use the fromkeys() method.
Output:
If you have a list of lists, where each inner list contains two elements (key and value), you can
use a list comprehension or dict() to convert it.
Output:
If you have a list of objects, and each object has attributes that you want to map as keys and their
respective values as dictionary values, you can use a loop or list comprehension.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Output:
Summary:
● Two Lists (keys and values): Use zip() to combine them into a dictionary.
● List of Tuples: Directly convert it with dict().
● List of Keys: Use a dictionary comprehension or fromkeys() to create a dictionary
with default values.
● List of Lists: Use dict() to convert.
● List of Objects: Use list comprehension to generate key-value pairs.
Converting strings into dictionaries can be done in various ways depending on the format and
structure of the string. Below are some common methods to convert strings into dictionaries in
Python:
If you have a string that represents key-value pairs in a format similar to a dictionary, you can
use eval(), ast.literal_eval(), or json.loads() to safely convert it into a
dictionary.
If the string is formatted exactly like a dictionary (with curly braces, key-value pairs, etc.), you
can use eval() to evaluate the string as a Python expression.
string = "{'name': 'Alice', 'age': 30, 'city': 'New York'}"
# Using eval() to convert the string into a dictionary
my_dict = eval(string)
print(my_dict)
Output:
Note: eval() can be dangerous if the string comes from an untrusted source, as it executes
arbitrary code. A safer alternative is ast.literal_eval().
import ast
string = "{'name': 'Alice', 'age': 30, 'city': 'New York'}"
# Using ast.literal_eval() to safely convert the string into a
dictionary
my_dict = ast.literal_eval(string)
print(my_dict)
Output:
Output:
Note: The parse_qs() function returns the values as lists. If you want to convert the lists to
strings, you can process the output like this:
Output:
If the string contains key-value pairs separated by commas or other delimiters, you can split the
string and then process each pair.
Output:
{'name': 'Alice', 'age': '30', 'city': 'New York'}
You can use a custom delimiter to split the string into key-value pairs. For example, if the string
uses a colon (:) to separate keys and values, you can process it as follows:
Output:
If you have a string in JSON format, you can use json.loads() to parse the string into a
dictionary.
import json
string = '{"name": "Alice", "age": 30, "city": "New York"}'
# Using json.loads() to convert the JSON string into a
dictionary
my_dict = json.loads(string)
print(my_dict)
Output:
{'name': 'Alice', 'age': 30, 'city': 'New York'}
If the string has an irregular pattern, you can use regular expressions to extract the key-value
pairs and convert them to a dictionary.
import re
string = "name=Alice;age=30;city=New York"
# Using regular expressions to extract key-value pairs
my_dict = dict(re.findall(r'(\w+)=(\w+|\w+ \w+)', string))
print(my_dict)
Output:
Summary:
In Python, dictionaries can be passed to functions in the same way as other data types. You can
pass them as arguments, modify them within the function, and return them. Here's a breakdown
of how to pass and work with dictionaries in functions:
1. Passing a Dictionary as a Function Argument
You can pass a dictionary to a function by simply passing it as an argument. The function can
then access the dictionary and modify it if necessary.
def print_person_info(person):
print(f"Name: {person['name']}, Age: {person['age']}, City:
{person['city']}")
# Create a dictionary
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
Output:
Since dictionaries are mutable, any modifications made to the dictionary inside the function will
affect the original dictionary outside the function.
def update_age(person):
person['age'] = 35 # Modify the dictionary directly
# Create a dictionary
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
Output:
You can also pass a dictionary as keyword arguments to a function using the **kwargs syntax.
This allows you to pass the dictionary keys as function arguments.
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Create a dictionary
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
Output:
name: Alice
age: 30
city: New York
In this case, the **person syntax unpacks the dictionary into keyword arguments.
4. Returning a Dictionary from a Function
A function can return a dictionary as a result. You can either create a new dictionary inside the
function or modify and return the original dictionary.
Output:
You can pass multiple dictionaries to a function and combine them or perform other operations
on them.
Output:
Dictionaries can also be used as default arguments in functions, but be cautious when using
mutable types (like dictionaries) as default arguments because they retain changes across
function calls.
Summary:
● Passing a dictionary: You can pass it directly or use **kwargs to pass it as keyword
arguments.
● Modifying inside a function: Changes to the dictionary will reflect outside the function,
as dictionaries are mutable.
● Returning a dictionary: Functions can return a dictionary.
● Merging dictionaries: You can pass multiple dictionaries and merge them.
● Using dictionaries as default arguments: Be cautious of shared mutable defaults.
Ordered Dictionaries
In Python, Ordered Dictionaries are a type of dictionary that maintains the insertion order of
keys. Python's built-in dict type also preserves insertion order starting from Python 3.7.
However, the collections.OrderedDict class provides additional functionality and
guarantees.
The OrderedDict class in the collections module explicitly ensures that the insertion
order of items is maintained.
Example:
# Creating an OrderedDict
ordered_dict = OrderedDict()
# Adding items
ordered_dict['apple'] = 3
ordered_dict['banana'] = 2
ordered_dict['cherry'] = 5
# Accessing items
print(ordered_dict)
Output:
Preserves Order:
● Python 3.7+: The built-in dict type also maintains insertion order.
● Before Python 3.7: Regular dict did not guarantee any order of keys.
Example:
If you're using Python 3.7 or later, for most cases, you don't need OrderedDict unless you
specifically require its additional methods.
The OrderedDict provides additional methods and behaviors that are not available with
regular dictionaries:
B. Equality Comparisons
Unlike regular dictionaries, OrderedDict considers the order of items when testing equality.
The popitem() method in OrderedDict removes and returns items either in LIFO (Last In,
First Out) or FIFO (First In, First Out) order.
D. Reversibility
Output:
cherry 5
banana 2
apple 3
You can easily convert a regular dictionary into an OrderedDict to take advantage of its
features.
Output:
5. Sorting an OrderedDict
You can sort an OrderedDict by its keys or values using a sorted() function and recreate
it.
Sort by Keys:
Output:
Sort by Values:
# Sort by values
sorted_dict = OrderedDict(sorted(ordered_dict.items(),
key=lambda x: x[1]))
print(sorted_dict)
Output:
● You are using Python versions earlier than 3.7 and need guaranteed insertion order.
● You need advanced features like move_to_end(), ordered equality comparisons, or
specific popitem behavior.
For most modern Python codebases (3.7+), the built-in dict is sufficient unless these additional
features are explicitly required