Strings in Python
In Python, strings are sequences of characters enclosed in single quotes (') or double quotes
("). They are immutable, meaning you cannot change individual characters within a string.
Basic String Operations:
1. Concatenation: Combining strings using the + operator.
first_name = "Alice"
last_name = "Johnson"
full_name = first_name + " " + last_name
print(full_name) # Output: Alice Johnson
2. String Length: Using the len() function.
greeting = "Hello, world!"
length = len(greeting)
print(length) # Output: 13
3. String Indexing: Accessing individual characters using square brackets.
word = "Python"
first_char = word[0] # Access the first character
last_char = word[-1] # Access the last character
print(first_char, last_char) # Output: P n
4. String Slicing: Extracting a portion of a string.
sentence = "This is a Python string"
substring = sentence[7:13] # Extract "is a Py"
print(substring)
5. String Methods: Python provides various string methods for manipulation.
o upper(): Converts to uppercase.
o lower(): Converts to lowercase.
o strip(): Removes leading and trailing whitespace.
o split(): Splits a string into a list of substrings based on a delimiter.
o join(): Joins elements of a list or tuple into a string.
o replace(): Replaces occurrences of a substring with another.
o find(): Finds the index of the first occurrence of a substring.
o count(): Counts the occurrences of a substring.
Example:
text = " Hello, World! "
print(text.strip()) # Remove whitespace
print(text.upper()) # Convert to uppercase
print(text.split()) # Split into a list of words
print(text.replace("World", "Python")) # Replace "World" with "Python"
Lists in Python
Lists are one of the most versatile data structures in Python, used to store collections of items.
They are ordered and mutable, meaning you can change their elements and their order.
Creating a List:
my_list = [1, 2, 3, "apple", "banana"]
Accessing Elements:
You can access individual elements using indexing, starting from 0:
first_element = my_list[0] # Access the first element
last_element = my_list[-1] # Access the last element
Slicing Lists:
You can extract a portion of a list using slicing:
sublist = my_list[1:4] # Extract elements from index 1 to 3 (exclusive)
Modifying Lists:
Appending: Add an element to the end:
my_list.append("cherry")
Inserting: Add an element at a specific index:
my_list.insert(2, "orange")
Removing: Remove an element by value or index:
my_list.remove("apple")
my_list.pop(1) # Remove the element at index 1
Modifying Elements:
my_list[0] = 10
Iterating Over a List:
for item in my_list:
print(item)
List Operations in Python
Python offers a wide range of operations to manipulate lists. Here are some of the most
common ones:
Basic Operations:
Accessing Elements:
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Access the first element
print(my_list[-1]) # Access the last element
Slicing:
sublist = my_list[1:4] # Extract elements from index 1 to 3
(exclusive)
Length:
length = len(my_list)
Modifying Lists:
Appending:
my_list.append(6) # Add 6 to the end
Inserting:
my_list.insert(2, 10) # Insert 10 at index 2
Removing:
my_list.remove(3) # Remove the first occurrence of 3
my_list.pop(1) # Remove the element at index 1
Modifying Elements:
my_list[0] = 100
List Methods:
sort(): Sorts the list in ascending order.
reverse(): Reverses the order of elements.
count(x): Counts the occurrences of x in the list.
index(x): Returns the index of the first occurrence of x.
clear(): Removes all elements from the list.
copy(): Creates a shallow copy of the list.
Tuples in Python
Tuples are similar to lists, but they are immutable, meaning their elements cannot be changed
once the tuple is created. They are often used to store related data that should not be
modified.
Creating a Tuple:
my_tuple = (1, 2, 3, "apple", "banana")
Accessing Elements:
Like lists, you can access elements using indexing:
first_element = my_tuple[0] # Access the first element
last_element = my_tuple[-1] # Access the last element
Basic Tuple Operations in Python
While tuples are immutable, they still offer several operations to work with their elements:
1. Accessing Elements:
Use indexing to access individual elements:
my_tuple = (1, 2, 3, "apple", "banana")
print(my_tuple[0]) # Output: 1
print(my_tuple[-1]) # Output: banana
2. Slicing:
Extract a portion of a tuple:
subtuple = my_tuple[1:4] # Output: (2, 3, 'apple')
3. Concatenation:
Combine two tuples using the + operator:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2 # Output: (1, 2, 3, 4, 5, 6)
4. Repetition:
Repeat a tuple using the * operator:
repeated_tuple = tuple1 * 3 # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
5. Length:
Determine the number of elements using the len() function:
length = len(my_tuple)
6. Membership Testing:
Check if an element exists in a tuple using the in and not in operators:
if "apple" in my_tuple:
print("Apple is present")
7. Tuple Methods:
count(x): Counts the occurrences of x in the tuple.
index(x): Returns the index of the first occurrence of x.
Example:
my_tuple = (10, 20, 30, 40, 50)
# Accessing elements
print(my_tuple[2]) # Output: 30
# Slicing
print(my_tuple[1:4]) # Output: (20, 30, 40)
# Concatenation
new_tuple = my_tuple + (60, 70)
print(new_tuple) # Output: (10, 20, 30, 40, 50, 60, 70)
# Counting elements
count = my_tuple.count(20)
print(count) # Output: 1
# Finding index
index = my_tuple.index(40)
print(index) # Output: 3
Dictionaries in Python
Dictionaries are a fundamental data structure in Python, used to store key-value pairs. Each
key is unique, and it maps to a specific value.
Creating a Dictionary:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
Dictionary Operations in Python
Dictionaries in Python offer a variety of operations to manipulate and access key-value pairs.
Here are some common operations:
1. Accessing Values:
Use the key to access the corresponding value:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict["name"]) # Output: Alice
2. Adding or Modifying Key-Value Pairs:
Add a new key-value pair:
my_dict["country"] = "USA"
Modify an existing value:
my_dict["age"] = 31
3. Removing Key-Value Pairs:
Use the del keyword:
del my_dict["city"]
Use the pop() method to remove and return a value:
value = my_dict.pop("age")
4. Checking Key Existence:
Use the in keyword:
if "name" in my_dict:
print("Name exists")
5. Iterating Over a Dictionary:
Iterate over keys:
for key in my_dict:
print(key)
Iterate over values:
for value in my_dict.values():
print(value)
Iterate over key-value pairs:
for key, value in my_dict.items():
print(key, value)
6. Common Dictionary Methods:
keys(): Returns a view of the dictionary's keys.
values(): Returns a view of the dictionary's values.
items(): Returns a view of the dictionary's key-value pairs as tuples.
get(key,
default): Returns the value for the key if it exists, otherwise returns the default
value.
clear(): Removes all key-value pairs from the dictionary.
Example
person = {"name": "Bob", "age": 25, "grades": {"Math": 90, "Science": 85}}
# Accessing values
print(person["name"]) # Output: Bob
print(person["grades"]["Math"]) # Output: 90
# Adding a new key-value pair
person["city"] = "New York"
# Removing a key-value pair
del person["age"]
# Iterating over key-value pairs
for key, value in person.items():
print(key, value)
Sets in Python
Sets are unordered collections of unique elements. They are useful for removing duplicates
and performing set operations like union, intersection, and difference.
Creating a Set:
my_set = {1, 2, 3, 3, 4, 5} # Duplicates are removed
print(my_set) # Output: {1, 2, 3, 4, 5}
Adding Elements:
my_set.add(6)
Removing Elements:
my_set.remove(3) # Removes 3
my_set.discard(7) # Doesn't raise an error if 7 is not present
Set Operations:
1. Union:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # or set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
2. Intersection:
intersection_set = set1.intersection(set2) # or set1 & set2
print(intersection_set) # Output: {3}
3. Difference:
difference_set = set1.difference(set2) # or set1 - set2
print(difference_set) # Output: {1, 2}
4. Symmetric Difference:
symmetric_difference_set = set1.symmetric_difference(set2) # or set1
^ set2
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
Checking Set Relationships:
Subset:
set1 = {1, 2}
set2 = {1, 2, 3, 4}
print(set1.issubset(set2)) # Output: True
Superset:
print(set2.issuperset(set1)) # Output: True
Disjoint:
set3 = {5, 6, 7}
print(set1.isdisjoint(set3)) # Output: True