Skip to main content

Data Structures in Python

Data Structures in Python

Data structures are a fundamental aspect of programming that allow you to organize and store data efficiently. Python provides several built-in data structures that are versatile and easy to use, such as lists, tuples, dictionaries, and sets. Each data structure has its own unique properties, and it is important to understand when to use each one.

6.1 Lists

Lists are ordered, mutable collections of items. They can store any type of data (integers, strings, objects) and allow for duplication of elements. Lists are defined using square brackets [].

# Example of a list
fruits = ["apple", "banana", "cherry", "apple"]
print(fruits)

6.1.1 List Operations

Some common list operations include:

  • append(): Adds an item to the end of the list.
  • insert(): Inserts an item at a specific position.
  • remove(): Removes the first occurrence of an item.
  • pop(): Removes and returns the last item in the list.
  • sort(): Sorts the list in place.
# List operations example
fruits.append("orange")
fruits.remove("banana")
print(fruits)
fruits.sort()
print(fruits)

6.1.2 List Slicing

List slicing allows you to access a portion of the list by specifying a range of indices.

# List slicing
numbers = [1, 2, 3, 4, 5, 6]
print(numbers[2:5])  # Output: [3, 4, 5]
print(numbers[:4])   # Output: [1, 2, 3, 4]
print(numbers[3:])   # Output: [4, 5, 6]

6.2 Tuples

Tuples are similar to lists but are immutable, meaning they cannot be modified after their creation. Tuples are defined using parentheses ().

# Example of a tuple
person = ("John", 25, "Engineer")
print(person)

6.2.1 Tuple Unpacking

Tuple unpacking allows you to assign the values in a tuple to multiple variables at once.

# Tuple unpacking
name, age, profession = person
print(name)
print(age)
print(profession)

6.2.2 Tuples vs. Lists

Tuples are used when you want a collection of data that should not change, while lists are used when you need a mutable collection. Tuples can be slightly faster than lists due to their immutability.

6.3 Dictionaries

Dictionaries are unordered, mutable collections of key-value pairs. They are defined using curly braces {} and allow you to associate a value with a unique key.

# Example of a dictionary
person = {
    "name": "Alice",
    "age": 30,
    "profession": "Doctor"
}
print(person["name"])

6.3.1 Adding and Modifying Values

You can add new key-value pairs or modify existing ones in a dictionary.

# Adding and modifying values in a dictionary
person["city"] = "New York"
person["age"] = 31
print(person)

6.3.2 Dictionary Methods

  • keys(): Returns a list of all keys in the dictionary.
  • values(): Returns a list of all values in the dictionary.
  • items(): Returns a list of key-value pairs as tuples.
# Dictionary methods
print(person.keys())
print(person.values())
print(person.items())

6.4 Sets

Sets are unordered collections of unique elements. They are defined using curly braces {} and do not allow duplicate values.

# Example of a set
fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)  # Output: {"apple", "banana", "cherry"}

6.4.1 Set Operations

Sets support mathematical operations like union, intersection, and difference.

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}

print(set1.union(set2))       # Union: {1, 2, 3, 4, 5}
print(set1.intersection(set2))# Intersection: {3}
print(set1.difference(set2))  # Difference: {1, 2}

6.5 List Comprehensions

List comprehensions provide a concise way to create lists. They are often used to apply an expression to each item in a sequence.

# Example of list comprehension
squares = [x**2 for x in range(10)]
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

6.5.1 Conditional List Comprehensions

List comprehensions can also include conditions.

# Conditional list comprehension
evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # Output: [0, 2, 4, 6, 8]

6.6 Dictionary Comprehensions

Like list comprehensions, Python supports dictionary comprehensions for creating dictionaries in a concise way.

# Example of dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Comments

Popular posts from this blog

How to Add External Libraries (JAR files) in Eclipse

How to Add External Libraries (JAR files) in Eclipse Adding external libraries (JAR files) to your Eclipse project allows you to use third-party code in your application. This guide will explain what JAR files are, how they differ from `.java` files, where to download them, and how to add them to your project. What are JAR Files? JAR (Java ARchive) files are package files that aggregate many Java class files and associated metadata and resources (such as text, images, etc.) into a single file for distribution. They are used to distribute Java programs and libraries in a platform-independent format, making it easier to share and deploy Java applications. Difference between .java and .jar Files .java files are source files written in the Java programming language. They contain human-readable Java code that developers write. In contrast, .jar files are compile...

Managing Hierarchical Structures: OOP vs Nested Maps in Java

Managing Hierarchical Structures: OOP vs Nested Maps in Java This topic explores the pros and cons of managing hierarchical data using Object-Oriented Programming (OOP) versus nested map structures in Java. This discussion is contextualized with an example involving a chip with multiple cores and sub-cores. Nested Map of Maps Approach Using nested maps to manage hierarchical data can be complex and difficult to maintain. Here’s an example of managing a chip with cores and sub-cores using nested maps: Readability and Maintainability: Nested maps can be hard to read and maintain. The hierarchy is not as apparent as it would be with OOP. Encapsulation: The nested map approach lacks encapsulation, leading to less modular and cohesive code. Error-Prone: Manual management of keys and values increases the risk of errors, such as NullPointerExce...

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration 1. Compiling a C Program to an Executable Step 1: Write a C Program #include <stdio.h> int main() { printf("Hello, World!\\n"); return 0; } Step 2: Compile the C Program gcc -o example example.c 2. Executing the C Program in the Console Step 3: Run the Executable ./example 3. Including Shared .so Libraries Step 4: Create a Shared Library #include <stdio.h> void my_function() { printf("Shared Library Function Called!\\n"); } gcc -shared -o libmylib.so -fPIC mylib.c Step 5: Update the C Program to Use the Shared Library #include <stdio.h> void my_function(); int main() { my_function(); printf("Hello, World!\\n...