DEV Community

Cover image for A Guide to Python Lists, Tuples, Dictionaries, and Sets
Varsha VM
Varsha VM

Posted on

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.

ComparisonOfPythonDatastructures

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"]
Enter fullscreen mode Exit fullscreen mode

Accessing Elements

print(flowers[0])  # Output: rose
Enter fullscreen mode Exit fullscreen mode

Modifying Elements

flowers[1] = "lotus"
print(flowers)  # Output: ['rose', 'lotus']
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode
  • 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']
Enter fullscreen mode Exit fullscreen mode
  • 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']
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
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']
Enter fullscreen mode Exit fullscreen mode
  • 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: ['dahlia', 'daisy', 'hibiscus', 'lilly', 'rose', 'sunflower']
flowers.sort(reverse=True)
print(flowers) 
# Output: ['sunflower', 'rose', 'lilly', 'hibiscus', 'daisy', 'dahlia']
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode
  • 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']
Enter fullscreen mode Exit fullscreen mode
  • 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']
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Accessing Elements

print(coordinates[0])  # Output: 10
Enter fullscreen mode Exit fullscreen mode

Tuple Methods

  • count(): Returns the number of occurrences of a specified value.
coordinates.count(10)  # Output: 1
Enter fullscreen mode Exit fullscreen mode
  • index(): Returns the index of the first occurrence of a specified value.
coordinates.index(10)  # 0
Enter fullscreen mode Exit fullscreen mode

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"]}
Enter fullscreen mode Exit fullscreen mode

Accessing Elements

print(student["name"])  # Output: John
Enter fullscreen mode Exit fullscreen mode

Adding Elements

student["year"] = 2024
print(student)  
# Output: {'name': 'VV', 'age': 22, 'courses': ['Math', 'Science'], 'year': 2024}
Enter fullscreen mode Exit fullscreen mode

Modifying Elements

student["age"] = 44
print(student["age"])  # Output: 44
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode
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)]
Enter fullscreen mode Exit fullscreen mode
  • 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']
Enter fullscreen mode Exit fullscreen mode
  • 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]
Enter fullscreen mode Exit fullscreen mode
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}
Enter fullscreen mode Exit fullscreen mode
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}
Enter fullscreen mode Exit fullscreen mode
  • clear(): Removes all key-value pairs in a dictionary
# syntax: dict_name.clear() 
student.clear()
print(student) # Output: {}
Enter fullscreen mode Exit fullscreen mode

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"}
Enter fullscreen mode Exit fullscreen mode

Set Methods

Adding Elements
  • add(): Adds an element to a set.
# syntax: set_name.add(element) 
colors.add("green")
print(colors) # Output: {'red', 'green'}
Enter fullscreen mode Exit fullscreen mode
  • 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'}
Enter fullscreen mode Exit fullscreen mode

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'}
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
  • issuperset(): Checks if the current set is a superset of another set.
# syntax: set_name.issuperset(set2) 
colors.issuperset({"green", "red"}) # Output: True
Enter fullscreen mode Exit fullscreen mode
  • isdisjoint(): Two sets are disjoint if they have no elements in common.
# syntax: set_name.isdisjoint(set2) 
colors.isdisjoint({"green", "red"}) # Output: False
Enter fullscreen mode Exit fullscreen mode
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'}
Enter fullscreen mode Exit fullscreen mode
  • 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'
Enter fullscreen mode Exit fullscreen mode
  • 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'}
Enter fullscreen mode Exit fullscreen mode
  • 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()
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode
  • 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}
Enter fullscreen mode Exit fullscreen mode
  • 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}
Enter fullscreen mode Exit fullscreen mode
  • 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}
Enter fullscreen mode Exit fullscreen mode

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)