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
Post a Comment