Overview
Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation.
Lists
- A list is any list of data items, separated by commas, inside square brackets.
- They are ordered, mutable, and allow duplicate elements. Lists can store elements of different data types.
Creating a List
flowers = ["rose", "lilly"]
Accessing Elements
print(flowers[0]) # Output: rose
Modifying Elements
flowers[1] = "lotus"
print(flowers) # Output: ['rose', 'lotus']
List Methods
Adding Elements
- append(): Used to add an element to the end of a list.
# syntax: list_name.append(element)
flowers.append("hibiscus")
print(flowers)
# Output: ['rose', 'lilly', 'hibiscus']
- extend(): Used to add multiple elements to a list. Takes an iterable as an argument
# syntax: list_name.extend(iterable)
flowers.extend(["daisy", "dahlia"])
print(flowers)
# Output: ['rose', 'lilly', 'hibiscus', 'daisy', 'dahlia']
- insert(): Used to insert an element at the specified index.
# syntax: list_name.insert(index, element)
flowers.insert(2, "sunflower")
print(flowers)
# Output: ['rose', 'lilly', 'sunflower', 'hibiscus', 'daisy', 'dahlia']
Comparison
- append(): Adds a single element.
- extend(): Adds multiple elements.
- insert(): Adds an element at a specific position.
List Analysis
- copy(): Create a shallow copy of a list.
# syntax: list_name.copy()
new_list = flowers.copy()
print(new_list)
# Output: ['rose', 'lilly', 'sunflower', 'hibiscus', 'daisy', 'dahlia']
- count(): Used to count the number of occurrences of a specific element in a list
# syntax: list_name.count(element)
flowers.count("hibiscus") # Output: 1
Reordering Elements
- reverse(): Used to reverse the order of elements in a list.
# syntax: list_name.reverse()
flowers.reverse()
print(flowers)
# Output: ['dahlia', 'daisy', 'hibiscus', 'sunflower', 'lilly', 'rose']
-
sort(): Used to sort the elements of a list in ascending order. If you want to sort the list in descending order, you can pass the
reverse=True
argument to thesort()
method.
# syntax: list_name.sort()
flowers.sort()
print(flowers)
# Output: ['dahlia', 'daisy', 'hibiscus', 'lilly', 'rose', 'sunflower']
flowers.sort(reverse=True)
print(flowers)
# Output: ['sunflower', 'rose', 'lilly', 'hibiscus', 'daisy', 'dahlia']
Comparison
- reverse(): Reverses the list in place.
- sort(): Sorts the list in place, with optional descending order.
Removing Elements
- del: Removes the element at the specified index.
# syntax: del list_name[index]
del flowers[1]
print(flowers)
# Output: ['sunflower', 'lilly', 'hibiscus', 'daisy', 'dahlia']
- remove(): Used to remove an element. it removes the first occurrence of the specified value.
# syntax: list_name.remove(element)
flowers.remove("sunflower")
print(flowers)
# Output: ['lilly', 'hibiscus', 'daisy', 'dahlia']
-
pop(): Another way to remove an element from a list in Python. It removes and returns the element at the specified index. If you don't provide an index to the
pop()
method, it will remove and return the last element of the list by default
# syntax: list_name.remove(element)
flowers.pop() # Output: 'dahlia'
print(flowers)
# Output: ['lilly', 'hibiscus', 'daisy']
Comparison
- del: Removes by index without returning the element.
- remove(): Removes by value, only the first occurrence.
- pop(): Removes by index and returns the element.
Tuples
- Tuples are similar to lists, but they are immutable. An immutable object can't be changed after it is created.
- Tuples are useful for fixed collections of items.
Creating a Tuples
coordinates = (10, 20)
Accessing Elements
print(coordinates[0]) # Output: 10
Tuple Methods
- count(): Returns the number of occurrences of a specified value.
coordinates.count(10) # Output: 1
- index(): Returns the index of the first occurrence of a specified value.
coordinates.index(10) # 0
Dictionaries
- A dictionary in Python is a data structure that stores a collection of key-value pairs, where each key is unique and associated with a specific value.
- They are ordered, mutable, and indexed by keys.
- Dictionaries are highly efficient for lookups.
Creating a Dictionary
student = {"name": "VV", "age": 22, "courses": ["Math", "Science"]}
Accessing Elements
print(student["name"]) # Output: John
Adding Elements
student["year"] = 2024
print(student)
# Output: {'name': 'VV', 'age': 22, 'courses': ['Math', 'Science'], 'year': 2024}
Modifying Elements
student["age"] = 44
print(student["age"]) # Output: 44
Dictionary Methods
Creating and Copying
- copy(): Create a shallow copy of a list.
# syntax: new_dict = dict_name.copy()
new_dict = student.copy()
print(new_dict)
# Output: {'name': 'VV', 'age': 44, 'courses': ['Math', 'Science'], 'year': 2024}
Retrieving Elements
- items(): Retrieves all key-value pairs as tuples and converts them into a list of tuples. Each tuple consists of a key and its corresponding value.
# syntax: list(dict_name.items())
print(list(student.items()))
# Output: [('name', 'VV'), ('age', 44), ('courses', ['Math', 'Science']), ('year', 2024)]
- keys(): Retrieves all keys from the dictionary and converts them into a list.
# syntax: list(dict_name.keys())
print(list(student.keys()))
# Output: ['name', 'age', 'courses', 'year']
- values(): Retrieves all values from the dictionary and converts them into a list.
# syntax: list(dict_name.values())
print(list(student.values()))
# Output: ['VV', 44, ['Math', 'Science'], 2024]
Updating
- update(): Merges the provided dictionary into the existing dictionary, adding or updating key-value pairs.
# syntax: dict_name.update({key: value})
student.update({'year':2023,'dob':2000})
print(student)
# Output: {'name': 'VV', 'age': 44, 'courses': ['Math', 'Science'], 'year': 2023, 'dob': 2000}
Removing Elements
-
del: Removes the specified key-value pair from the dictionary. Raises a
KeyError
if the key does not exist.
# syntax: del dict_name[key]
del student['courses']
print(student)
# Output: {'name': 'VV', 'age': 44, 'year': 2023, 'dob': 2000}
- clear(): Removes all key-value pairs in a dictionary
# syntax: dict_name.clear()
student.clear()
print(student) # Output: {}
Comparison
- del: Removes a specific key-value pair identified by the key.
- clear(): Removes all key-value pairs from the dictionary.
Sets
- A set is an unordered collection of unique elements.
- They are unordered, unchangeable, and unindexed.
- Sets support mathematical operations like union, intersection, and difference.
- Sets are mostly used for membership testing and eliminating duplicate entries
Creating a Set:
colors = {"red"}
Set Methods
Adding Elements
- add(): Adds an element to a set.
# syntax: set_name.add(element)
colors.add("green")
print(colors) # Output: {'red', 'green'}
- update(): Adds elements from another iterable into the set
# syntax: set_name.update(iterable)
colors.update({"green", "red", "yellow"})
print(new_set) # Output: {'green', 'yellow', 'red'}
Comparison
- add(): Adds a single element to the set.
- update(): Adds multiple elements from an iterable to the set.
Copying
- copy(): Creates a shallow copy of the set.
# syntax: new_set = set_name.copy()
new_set = colors.copy()
print(new_set) # Output: {'red', 'green', 'yellow'}
Subset, Superset, and Disjoint Check
- issubset(): Checks if the current set is a subset of another set.
# syntax: set_name.issubset(set2)
colors.issubset({"green", "red"}) # Output: False
- issuperset(): Checks if the current set is a superset of another set.
# syntax: set_name.issuperset(set2)
colors.issuperset({"green", "red"}) # Output: True
- isdisjoint(): Two sets are disjoint if they have no elements in common.
# syntax: set_name.isdisjoint(set2)
colors.isdisjoint({"green", "red"}) # Output: False
Removing Elements
- discard(): Remove a specific element from the set. Ignores if the element is not found.
# syntax: set_name.discard(element)
colors.discard("red")
print(colors) # Output: {'green', 'yellow'}
-
pop(): Removes and returns an arbitrary element from the set. It raises a
KeyError
if the set is empty
# syntax: removed_element = set_name.pop()
colors.pop() # Output: 'green'
-
remove(): Remove a specific element from the set. Raises a
KeyError
if the element is not found.
# syntax: set_name.remove(element)
new_set.remove('green')
print(colors) # Output: {'red', 'yellow'}
- clear(): Removes all elements from the set. It updates the set in-place.
# syntax: set_name.clear()
new_set.clear()
print(new_set) # Output: set()
Comparison
- discard(): Removes an element if present, does nothing if the element is not found.
- pop(): Removes and returns an arbitrary element, raises an error if the set is empty.
- remove(): Removes an element if present, raises an error if the element is not found.
- clear(): Removes all elements from the set.
Set Operations
- Union: The union of two sets is a set containing all elements from both sets, without duplicates.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Method 1: Using the | operator
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5, 6}
# Method 2: Using the union() method
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5, 6}
- Intersection: The intersection of two sets is a set containing only the elements that are present in both sets.
# Method 1: Using the & operator
intersection_set = set1 & set2
print(intersection_set) # Output: {3, 4}
# Method 2: Using the intersection() method
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3, 4}
- Difference: The difference between two sets is a set containing the elements that are present in the first set but not in the second set.
# Method 1: Using the - operator
difference_set = set1 - set2
print(difference_set) # Output: {1, 2}
# Method 2: Using the difference() method
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
- Symmetric Difference: The symmetric difference between two sets is a set containing the elements that are in either of the sets but not in both.
# Method 1: Using the ^ operator
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # Output: {1, 2, 5, 6}
# Method 2: Using the symmetric_difference() method
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 5, 6}
Comparison
- union(): Combines elements from two sets.
- intersection(): Finds common elements between sets.
- difference(): Finds elements in one set but not the other.
- symmetric_difference(): Finds elements in either set but not in both.
Conclusion
Understanding and using the right data structures is key to writing efficient and effective Python code. Each data structure has its own strengths and use cases, from the flexible and dynamic lists to the fast and efficient dictionaries.
If you have any questions, suggestions, or corrections, please feel free to leave a comment. Your feedback helps me improve and create more accurate content.
Happy coding!!!
Top comments (0)