A Guide to Python Lists, Tuples, Dictionaries, and Sets

A Guide to Python Lists, Tuples, Dictionaries, and Sets

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

append(): Used to add an element to the end of a list.

# syntax: list_name.append(element)
flowers.append(hibiscus)

copy(): Create a shallow copy of a list.

# syntax: list_name.copy()
new_list = flowers.copy()
print(new_list) # Output: [‘rose’, ‘lotus’, ‘hibiscus’]

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

del: Removes the element at the specified index.

# syntax: del list_name[index]
del flowers[1]
print(flowers) # Output: [‘rose’, ‘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’, ‘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’, ‘hibiscus’, ‘sunflower’, ‘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: [‘rose’, ‘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: [‘rose’, ‘hibiscus’, ‘daisy’]

reverse(): Used to reverse the order of elements in a list.

# syntax: list_name.reverse()
flowers.reverse()
print(flowers) # Output: [‘daisy’, ‘hibiscus’, ‘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 the sort() method.

# syntax: list_name.sort()
flowers.sort()
print(flowers) # Output: [‘daisy’, ‘hibiscus’, ‘rose’]
flowers.sort(reverse=True)
print(flowers) # Output: [‘rose’, ‘hibiscus’, ‘daisy’]

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

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’: 22, ‘courses’: [‘Math’, ‘Science’], ‘year’: 2024}

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’: 22, ‘year’: 2024}

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’, 22), (‘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’, ‘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’, 22, 2024]

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’: 22, ‘year’: 2023, ‘dob’: 2000}

clear(): Removes all key-value pairs in a dictionary

# syntax: dict_name.clear()
student.clear()
print(student) # Output: {}

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

add(): Adds an element to a set.

# syntax: set_name.add(element)
colors.add(green)
print(colors) # Output: {‘green’, ‘red’}

copy(): Creates a shallow copy of the set.

# syntax: new_set = set_name.copy()
new_set = colors.copy()
print(new_set) # Output: {‘green’, ‘red’}

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’}

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’}

update(): Adds elements from another iterable into the set

# syntax: set_name.update(iterable)
new_set.update({green, red})
print(new_set) # Output: {‘green’, ‘red’}

clear(): Removes all elements from the set. It updates the set in-place.

# syntax: set_name.clear()
new_set.clear()
print(new_set) # Output: {}

issubset(): Checks if the current set is a subset of another set.
Subset Check

# syntax: set_name.issubset(set2)
colors.issubset({green, red}) # Output: True

issuperset(): Checks if the current set is a superset of another set.
Superset Check

# syntax: set_name.issuperset(set2)
colors.issuperset({green, red}) # Output: False

isdisjoint(): Two sets are disjoint if they have no elements in common.
Disjoint Check

# syntax: set_name.issuperset(set2)
colors.issuperset({green, red}) # Output: False

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}

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!!!