Object Manipulation
Type Conversion
## Basic type conversions
integer_value = 42
string_value = str(integer_value)
float_value = float(integer_value)
list_value = list("LabEx")
Advanced Object Manipulation Methods
Copying Objects
import copy
## Shallow copy
original_list = [1, 2, 3]
shallow_copy = original_list.copy()
## Deep copy
nested_list = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(nested_list)
List Comprehensions
## Filtering and transforming objects
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = [x**2 for x in numbers if x % 2 == 0]
Object Iteration Techniques
Advanced Iteration Methods
## Enumerate and zip
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
combined = list(zip(numbers, letters))
Object Sorting and Ordering
Sorting Techniques
## Sorting objects
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
## Sort by grade
sorted_students = sorted(students, key=lambda x: x['grade'], reverse=True)
Object Manipulation Workflow
graph TD
A[Object Input] --> B[Transformation]
B --> C[Filtering]
C --> D[Sorting]
D --> E[Output]
Advanced Manipulation Techniques
Functional Programming Methods
## Map, filter, reduce
from functools import reduce
numbers = [1, 2, 3, 4, 5]
## Map: apply function to all elements
squared = list(map(lambda x: x**2, numbers))
## Filter: select elements based on condition
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
## Reduce: cumulative operation
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
Object Manipulation Patterns
Technique |
Purpose |
Example |
Mapping |
Transform elements |
[x*2 for x in list] |
Filtering |
Select specific elements |
[x for x in list if condition] |
Reducing |
Aggregate elements |
sum(list) |
Sorting |
Order elements |
sorted(list, key=function) |
- Use built-in methods for efficiency
- Leverage list comprehensions
- Consider memory usage
- Choose appropriate data structures
Best Practices for LabEx Developers
- Write clean, readable manipulation code
- Use functional programming techniques
- Optimize for performance
- Handle edge cases
- Use type hints and annotations
By mastering these object manipulation techniques, you'll become a more proficient Python developer in your LabEx projects.