Chapter 3: Data Structures in Python

Don't forget to explore our basket section filled with 15000+ objective type questions.

Data structures are fundamental components in programming that allow you to organize and manipulate data efficiently. Python provides several built-in data structures, including lists, tuples, dictionaries, and sets. This chapter explores these data structures in detail, discussing their properties, usage, and common operations.

Lists

A list is a versatile data structure in Python that can hold an ordered collection of items. Lists are defined using square brackets and can contain elements of different data types, including numbers, strings, and even other lists. Here's an example of creating a list:

fruits = ["apple", "banana", "orange"]

List elements are indexed starting from 0, which means you can access individual elements using their index. For instance:

print(fruits[0])  # Output: "apple"
print(fruits[1])  # Output: "banana"

Lists are mutable, meaning you can modify their elements after they are created. You can change an element's value, add new elements, or remove existing elements. Here are some common list operations:

# Modify an element
fruits[1] = "grape"

# Add an element at the end
fruits.append("kiwi")

# Insert an element at a specific index
fruits.insert(2, "pear")

# Remove an element
fruits.remove("apple")

# Get the length of a list
length = len(fruits)

# Check if an element exists in a list
if "orange" in fruits:
    print("Found!")

Tuples

A tuple is similar to a list, but it is immutable, meaning its elements cannot be modified once it is created. Tuples are defined using parentheses or without any delimiters. Here's an example:

point = (3, 4)

Tuples are commonly used to represent collections of related values, such as coordinates or database records. Although you cannot modify tuple elements, you can access them using indexing or unpacking:

x = point[0]
y = point[1]

# Unpacking
x, y = point

Dictionaries

A dictionary is an unordered collection of key-value pairs. Each value is associated with a unique key, which allows for efficient data retrieval. Dictionaries are defined using curly braces and can be created with or without initial values. Here's an example:

student = {
    "name": "John Doe",
    "age": 20,
    "major": "Computer Science"
}

To access values in a dictionary, you use the corresponding key. For example:

print(student["name"])  # Output: "John Doe"
print(student["age"])   # Output: 20

Dictionary values can be modified, new key-value pairs can be added, and existing pairs can be removed. Some common dictionary operations include:

# Modify a value
student["age"] = 21

# Add a new key-value pair
student["gpa"] = 3.8

# Remove a key-value pair
del student["major"]

# Check if a key exists in a dictionary
if "name" in student:
    print("Found!")

Sets

A set is an unordered collection of unique elements. It is defined using curly braces or the set() function. Sets are useful for eliminating duplicates and performing mathematical set operations like union, intersection, and difference. Here's an example:

fruits = {"apple", "banana", "orange"}

You can add elements to a set, remove elements, and perform set operations. Some common set operations include:

# Add an element
fruits.add("kiwi")

# Remove an element
fruits.remove("apple")

# Perform set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2       # Union: {1, 2, 3, 4, 5}
intersection = set1 & set2  # Intersection: {3}
difference = set1 - set2  # Difference: {1, 2}

Conclusion

This chapter provided an in-depth exploration of Python's built-in data structures: lists, tuples, dictionaries, and sets. You learned how to create and manipulate these structures, access their elements, and perform common operations. Understanding data structures is essential for effectively organizing and managing data in your programs. In the next chapter, we will dive into functions and modules, which are crucial for code organization, reusability, and modularity.

If you liked the article, please explore our basket section filled with 15000+ objective type questions.