Adventures in Machine Learning

Exploring Built-In and Custom Data Structures in Python

to Data Structures:

Data structures are a crucial aspect of computer science and programming, as they lay the foundation for organizing and manipulating data. Data structures are essentially a collection of data values, algorithms, and components that enable efficient storage and access to data.

They can range from simple structures like lists and arrays to more complex structures like trees and graphs. Python is a popular programming language that comes with built-in data structures that can be readily used in different projects.

In this article, we will explore the key built-in data structures in Python as well as some custom data structures commonly used in programming. Built-in Data Structures in Python:

Python comes with four fundamental built-in data structures, including lists, tuples, dictionaries, and sets.

We will briefly look at each of these data structures. Lists: Lists are mutable data structures used to store a collection of elements (strings, integers, or other objects) in a specific order.

Lists can be created using square brackets[] in Python. The list items are separated by commas and enclosed in square brackets.

Example: my_list = [1, 2, 3, ‘a’, ‘b’, ‘c’]

Tuples: Tuples are immutable data structures that are used to store a collection of elements in a specific order. Tuples can be created using parentheses () in Python.

The tuple items are separated by commas and enclosed in parentheses. Example: my_tuple = (1, 2, 3, ‘a’, ‘b’, ‘c’)

Dictionaries: Dictionaries are mutable data structures used to store key-value pairs.

Dictionaries are created using curly braces {} in Python. The key-value pairs are separated by colons and enclosed in curly braces.

Example: my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}

Sets: Sets are mutable data structures used to store a collection of unique elements. Sets can be created using curly braces {} or the set() function in Python.

Example: my_set = {‘a’, ‘b’, ‘c’} or my_set = set([‘a’, ‘b’, ‘c’])

Custom Data Structures:

Python comes with built-in data structures, but custom data structures can be created based on specific requirements. Some popular custom data structures in programming include stacks, queues, trees, linked lists, and graphs.

Stacks: A stack is a custom data structure that follows the Last-In-First-Out (LIFO) principle. It has two main operations: push (to add an item to the stack) and pop (to remove the last item from the stack).

Queues: A queue is a custom data structure that follows the First-In-First-Out (FIFO) principle. It has two main operations: enqueue (to add an item to the queue) and dequeue (to remove the first item from the queue).

Trees: A tree is a data structure that is composed of nodes connected by edges that represent relationships between the nodes. Trees have a hierarchical structure, with a single root node at the top and child nodes branching out from it.

Linked Lists: A linked list is a data structure composed of nodes that are connected through pointers. Each node contains a value and a pointer to the next node in the list.

Graphs: A graph is a data structure that represents relationships between objects. A graph consists of vertices (nodes) and edges (lines that connect the vertices).

List Data Structure:

List data structure is one of the most commonly used built-in data structures in Python. In this section, we will dive deeper into the details of lists.

Definition and Characteristics of Lists:

Lists are mutable and ordered data structures used to store a collection of values of any data type. The values in a list are enclosed in square brackets and separated by commas.

Lists can contain duplicate items, and they maintain their order of insertion. Creating a List:

Lists can be created using square brackets [] in Python.

The list items are separated by commas and enclosed in square brackets. The simplest way to create a list in Python is as follows:

Example: my_list = [1, 2, 3, ‘a’, ‘b’, ‘c’]

Accessing Items from a List:

Items in a list can be accessed using their corresponding index values.

Python uses a 0-based index system, which means the first item in a list has an index of 0, the second item has an index of 1, and so on. To access an item in a list, we use square brackets, and we pass the index value of the item as an argument.

Example: my_list = [1, 2, 3, ‘a’, ‘b’, ‘c’]

print(my_list[0]) # Output: 1

Adding and Removing Items from a List:

Adding items to a list is done with the append() method, which adds the item to the end of the list. You can also use the insert() method to add an item at a specific index position.

To remove an item from a list, we use the remove() method, which takes the item as an argument, or we use the del keyword to remove an item at a specific index position. Example: my_list = [1, 2, 3, ‘a’, ‘b’, ‘c’]

# Adding an item to the end of the list

my_list.append(‘d’)

print(my_list) # Output: [1, 2, 3, ‘a’, ‘b’, ‘c’, ‘d’]

# Adding an item at a specific index position

my_list.insert(2, ‘e’)

print(my_list) # Output: [1, 2, ‘e’, 3, ‘a’, ‘b’, ‘c’, ‘d’]

# Removing an item by value

my_list.remove(‘a’)

print(my_list) # Output: [1, 2, ‘e’, 3, ‘b’, ‘c’, ‘d’]

# Removing an item by index position

del my_list[0]

print(my_list) # Output: [2, ‘e’, 3, ‘b’, ‘c’, ‘d’]

Sorting a List:

Sorting a list can be done using the sort() method, which arranges the items in ascending order.

You can also sort a list in descending order by setting the reverse parameter to True. Example: my_list = [3, 2, 1, 6, 5, 4]

my_list.sort()

print(my_list) # Output: [1, 2, 3, 4, 5, 6]

# Sorting in descending order

my_list.sort(reverse=True)

print(my_list) # Output: [6, 5, 4, 3, 2, 1]

Finding the Length of a List:

To find the length of a list, we use the len() function, which returns the number of items in the list.

Example: my_list = [1, 2, 3, ‘a’, ‘b’, ‘c’]

print(len(my_list)) # Output: 6

Conclusion:

Data structures are an integral part of programming, and they help programmers to organize, store, and manipulate data efficiently. Python comes with built-in data structures that can be readily used in different projects, including lists, tuples, dictionaries, and sets.

Programmers can also create custom data structures based on specific requirements, such as stacks, queues, trees, linked lists, and graphs. Understanding data structures and their functionalities can help programmers to optimize their code and improve their efficiency.

Tuple Data Structure:

Previously, we explored lists as a built-in data structure in Python. In this section, we will discuss tuples, another essential data structure in Python.

Definition and Characteristics of Tuples:

A tuple is an immutable and ordered collection of elements separated by commas and enclosed in parentheses. Immutable means that once a tuple is created, its contents cannot be modified.

However, tuples can be used to store a range of data types, including strings, integers, and other objects. One notable characteristic of tuples is that they are faster and consume less memory than lists.

Creating a Tuple:

Tuples can be created in several ways, including by enclosing elements in parentheses and separating them with commas. Parentheses are not mandatory when creating a tuple, but they help make the code more readable.

Example: my_tuple = (1, 2, 3, ‘a’, ‘b’, ‘c’)

Accessing Items from a Tuple:

To access items in a tuple, we use indexing, which starts from 0 for the first element in the tuple. We use square brackets after the tuple name and the index location of the element we wish to access.

Example: my_tuple = (1, 2, 3, ‘a’, ‘b’, ‘c’)

print(my_tuple[2]) # Output: 3

Converting a Tuple to List:

In Python, tuples and lists share some similarities but have a few key differences. Since tuples are immutable, converting a tuple to a list can be useful for modifying its contents.

To convert a tuple to a list, we use the list() function. Example: my_tuple = (1, 2, 3, ‘a’, ‘b’, ‘c’)

my_list = list(my_tuple)

print(my_list) # Output: [1, 2, 3, ‘a’, ‘b’, ‘c’]

Reversing and Sorting a Tuple:

Since tuples are immutable, they cannot be modified directly.

However, we can always create a new tuple with its contents in a different order. To reverse a tuple, we use slicing notation [::-1].

To sort a tuple, we use the sorted() function. Example: my_tuple = (3, 2, 1)

reversed_tuple = my_tuple[::-1]

print(reversed_tuple) # Output: (1, 2, 3)

# Sorting a tuple

my_tuple = (3, 1, 2)

sorted_tuple = sorted(my_tuple)

print(sorted_tuple) # Output: (1, 2, 3)

Removing Elements from a Tuple:

Since tuples are immutable, we cannot remove elements from them directly.

However, we can convert a tuple to a list, remove the element, and convert it back to a tuple. Example: my_tuple = (‘a’, ‘b’, ‘c’)

my_list = list(my_tuple)

my_list.remove(‘a’)

new_tuple = tuple(my_list)

print(new_tuple) # Output: (‘b’, ‘c’)

Dictionary Data Structure:

Another built-in data structure in Python is the dictionary.

In this section, we will discuss the key aspects of dictionaries. Definition and Characteristics of Dictionaries:

Dictionaries are mutable data structures used to store collections of key-value pairs, where the keys are unique, immutable, and used to retrieve their corresponding values.

Dictionaries are enclosed in curly braces {} and have a key-value pair format: key:value. Dictionaries can store different data types such as strings, integers, and lists.

Creating a Dictionary:

To create a dictionary, we use curly braces {} and separate the key-value pairs with a colon. We can also use the dictionary() constructor to create a dictionary.

Example: my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}

Accessing Items from a Dictionary:

To access the value of a specific key in a dictionary, we use the square-bracket notation [] and pass the key we want to retrieve. Example: my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}

print(my_dict[‘name’]) # Output: John

Finding the Length of a Dictionary:

To find the length of a dictionary, we use the len() function, which returns the number of key-value pairs within the dictionary.

Example: my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}

print(len(my_dict)) # Output: 3

Sorting a Dictionary:

Dictionaries are inherently unordered collections. Therefore, sorting a dictionary implies sorting the keys based on their values.

We can sort a dictionary by calling the sorted() function with the dictionary keys as the argument. Example: my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}

sorted_dict = sorted(my_dict.keys())

print(sorted_dict) # Output: [‘age’, ‘gender’, ‘name’]

Adding and Removing Elements in a Dictionary:

Since dictionaries are mutable, adding and removing elements can be done using different methods.

To add a new key-value pair to a dictionary, we use the square-bracket notation []. Example: my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}

my_dict[‘city’] = ‘New York’

print(my_dict) # Output: {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’, ‘city’: ‘New York’}

To remove an item from a dictionary, we use the del keyword followed by the key to be deleted.

Example: my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}

del my_dict[‘name’]

print(my_dict) # Output: {‘age’: 25, ‘gender’: ‘male’}

Conclusion:

In conclusion, we have explored two additional built-in data structures in Python, tuples, and dictionaries. Tuples are immutable and ordered collections that offer a faster and less memory-consuming alternative to lists when we do not need to modify the contents.

Dictionaries, on the other hand, are mutable and unordered collections used to store key-value pairs. Understanding these data structures is essential in writing efficient code and developing robust applications.

Set Data Structure:

Sets are another built-in data structure in Python that is used to store an unordered collection of unique elements. Sets are ideal for situations where we want to store a collection of elements but do not care about their order, and we want to ensure that there are no duplicates.

Definition and Characteristics of Sets:

A set is an unordered collection of unique elements enclosed in curly braces {}. Sets are similar to lists and tuples, but with the following characteristics:

– Sets do not allow duplicate elements

– Sets are unordered, which means that they are not indexed

– Sets are mutable, which means that we can add or remove elements from them

Creating a Set:

To create a set in Python, we can enclose a list of elements in curly braces {}, or we can use the set() function.

Example: my_set = {1, 2, 3, ‘a’, ‘b’, ‘c’}

Accessing Items from a Set:

Since sets are unordered and not indexed, we cannot access elements by their index position. However, we can check if a specific element is present in a set using the in keyword.

Example: my_set = {1, 2, 3, ‘a’, ‘b’, ‘c’}

print(‘a’ in my_set) # Output: True

Finding the Length of a Set:

To find the number of elements in a set, we use the len() function, which returns the length of the set. Example: my_set = {1, 2, 3, ‘a’, ‘b’, ‘c’}

print(len(my_set)) # Output: 6

Sorting a Set:

Since sets are unordered, we cannot sort them directly.

However, we can convert a set to a sorted list and obtain a sorted collection. Example: my_set = {3, 2, 1}

sorted_set = sorted(my_set)

print(sorted_set) # Output: [1, 2, 3]

Adding and Removing Elements in a Set:

We can add elements to a set using the add() method or the update() method to add multiple elements.

We remove elements from a set using the remove() method, which takes the element to remove as an argument. Example: my_set = {1, 2, 3}

my_set.add(4)

print

Popular Posts