Pages

Tuesday, 21 March 2023

Python data structures : lists, tuples, sets, arrays, and dictionaries

Introduction: 
Python is a powerful programming language that offers several built-in data structures to store and manipulate data. Each data structure has its unique set of advantages and disadvantages, and selecting the right one for your application is essential. In this blog, we'll explore five of the most common data structures in Python: lists, tuples, sets, arrays, and dictionaries.
Python prigramming language

Lists: 

A list is a mutable sequence of elements enclosed in square brackets and separated by commas. Lists are one of the most commonly used data structures in Python due to their flexibility and simplicity. Lists can store different types of data, and the elements can be modified, added, or removed. 

Example:

# create a list
my_list = [1, 2, 3, 4, 5]

# print the list
print("Original List:", my_list)

# add an element to the end of the list
my_list.append(6)
print("List after appending an element:", my_list)

# insert an element at a specific index
my_list.insert(2, 7)
print("List after inserting an element:", my_list)

# remove an element from the list
my_list.remove(3)
print("List after removing an element:", my_list)

# remove the last element from the list
my_list.pop()
print("List after removing the last element:", my_list)

# reverse the list
my_list.reverse()
print("List after reversing the elements:", my_list)

# sort the list in ascending order
my_list.sort()
print("List after sorting in ascending order:", my_list)

# sort the list in descending order
my_list.sort(reverse=True)
print("List after sorting in descending order:", my_list)

# get the length of the list
print("Length of the list:", len(my_list))

# get the index of an element
print("Index of the element 4:", my_list.index(4))

# count the number of occurrences of an element
print("Number of occurrences of the element 2:", my_list.count(2))

# slice the list
print("Sliced list from index 2 to 4:", my_list[2:5])

Tuples: 

Tuples are similar to lists, but they are immutable, meaning that their elements cannot be modified, added, or removed. Tuples are enclosed in parentheses and separated by commas. Tuples are useful when you want to ensure that the data remains constant and unchanged. 

Example:

# Create a tuple
my_tuple = (1, 2, 3, 4, 5)

# Accessing values in a tuple
print("First element of tuple:", my_tuple[0])
print("Last element of tuple:", my_tuple[-1])

# Slicing a tuple
print("Sliced tuple:", my_tuple[1:4])

# Length of a tuple
print("Length of tuple:", len(my_tuple))

# Count occurrences of an element in a tuple
print("Number of 3's in tuple:", my_tuple.count(3))

# Find index of the first occurrence of an element in a tuple
print("Index of first occurrence of 3:", my_tuple.index(3))

# Convert a tuple to a list
my_list = list(my_tuple)
print("Tuple converted to list:", my_list)

# Concatenating two tuples
my_other_tuple = (6, 7, 8)
concatenated_tuple = my_tuple + my_other_tuple
print("Concatenated tuple:", concatenated_tuple)

# Unpacking a tuple into variables
a, b, c, d, e = my_tuple
print("Unpacked values:", a, b, c, d, e)

Sets: 


 A set is an unordered collection of unique elements enclosed in curly braces and separated by commas. Sets are useful when you need to work with a collection of items and eliminate any duplicates. 


Example:


# Define two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union of sets
union_set = set1.union(set2)
print("Union of set1 and set2:", union_set)

# Intersection of sets
intersection_set = set1.intersection(set2)
print("Intersection of set1 and set2:", intersection_set)

# Difference between sets
difference_set = set1.difference(set2)
print("Elements in set1 but not in set2:", difference_set)

# Symmetric difference between sets
symmetric_difference_set = set1.symmetric_difference(set2)
print("Elements in either set1 or set2, but not both:", symmetric_difference_set)

# Subset check
subset_check = set1.issubset(set2)
print("Is set1 a subset of set2:", subset_check)

# Superset check
superset_check = set1.issuperset(set2)
print("Is set1 a superset of set2:", superset_check)

# Disjoint check
disjoint_check = set1.isdisjoint(set2)
print("Are set1 and set2 disjoint:", disjoint_check)

Arrays: 


An array is a data structure that stores a fixed number of elements of the same data type. Unlike lists, arrays can only store elements of the same data type, and the size of the array is fixed at the time of creation. Arrays are more memory-efficient than lists, and they offer faster processing speed. 


Example:


# Declare an array
arr = [1, 2, 3, 4, 5]

# Accessing elements
print("The first element is:", arr[0])
print("The second element is:", arr[1])

# Updating elements
arr[2] = 6
print("The updated array is:", arr)

# Length of the array
print("The length of the array is:", len(arr))

# Adding elements
arr.append(7)
print("The array after adding an element is:", arr)

# Removing elements
arr.pop()
print("The array after removing the last element is:", arr)

# Slicing an array
print("The first three elements are:", arr[:3])

# Concatenating arrays
arr2 = [8, 9, 10]
arr3 = arr + arr2
print("The concatenated array is:", arr3)

# Reversing an array
arr3.reverse()
print("The reversed array is:", arr3)

# Sorting an array
arr3.sort()
print("The sorted array is:", arr3)

# Checking if an element exists in the array
if 5 in arr3:
    print("5 exists in the array")
else:
    print("5 does not exist in the array")

Dictionaries: 


 A dictionary is an unordered collection of key-value pairs enclosed in curly braces and separated by commas. Dictionaries are useful when you need to store data in a structured way and access it quickly.

Example: 


# create a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# access a value by key
print(my_dict['name'])  # output: John

# add a new key-value pair
my_dict['country'] = 'USA'

# update an existing value
my_dict['age'] = 26

# remove a key-value pair
del my_dict['city']

# check if a key is present in the dictionary
if 'name' in my_dict:
    print('Name is present in the dictionary')
else:
    print('Name is not present in the dictionary')

# iterate over keys and values
for key, value in my_dict.items():
    print(key, ':', value)

# get all the keys as a list
keys = list(my_dict.keys())
print(keys)

# get all the values as a list
values = list(my_dict.values())
print(values)

# get the number of key-value pairs in the dictionary
print(len(my_dict))

# clear all the key-value pairs from the dictionary
my_dict.clear()

# check if the dictionary is empty
if not my_dict:
    print('Dictionary is empty')
else:
    print('Dictionary is not empty')

Comparing the key features of data structures:

Data Structure Mutable? Ordered? Indexable? Iterable? Hashable? Example
List Yes Yes Yes Yes No fruits = ['apple', 'banana', 'cherry']
Tuple No Yes Yes Yes Yes person = ('John', 25, 'Male')
Set Yes No No Yes No letters = {'a', 'b', 'c', 'd'}
Array Yes Yes Yes Yes No import array; arr = array.array('i', [1, 2, 3])
Dictionary Yes No Yes Yes Keys only ages = {'John': 25, 'Alice': 22, 'Bob': 30}

Conclusion: 


Python offers several built-in data structures that can be used to store and manipulate data. Choosing the right data structure for your application depends on the type of data you need to store and how you need to manipulate it. Lists, tuples,

Please subscribe to my youtube channel for latest python tutorials and this article

No comments:

Post a Comment