Practical Conversion Examples
Real-World Scenarios of List Conversion
LabEx recommends understanding practical applications of list conversion to enhance your Python programming skills.
1. Data Processing and Analysis
## Convert and filter numeric data
raw_data = {'apple': 50, 'banana': 30, 'orange': 75, 'grape': 20}
high_value_fruits = [fruit for fruit, price in raw_data.items() if price > 40]
print(high_value_fruits) ## Output: ['apple', 'orange']
Numerical Computations
## Convert set to sorted list for calculations
temperature_set = {32, 45, 28, 39, 51}
sorted_temperatures = sorted(list(temperature_set))
print(sorted_temperatures) ## Output: [28, 32, 39, 45, 51]
2. Text Processing
String Manipulation
## Convert string to list of unique characters
text = "hello world"
unique_chars = list(set(text.replace(" ", "")))
print(sorted(unique_chars)) ## Output: ['d', 'e', 'h', 'l', 'o', 'r', 'w']
Word Counting
## Convert text to word frequency list
sentence = "python is awesome python is powerful"
word_freq = {}
for word in sentence.split():
word_freq[word] = word_freq.get(word, 0) + 1
frequency_list = list(word_freq.items())
print(frequency_list) ## Output: [('python', 2), ('is', 2), ('awesome', 1), ('powerful', 1)]
Nested Collection Conversion
## Convert nested dictionary to list of values
student_grades = {
'Alice': {'math': 90, 'science': 85},
'Bob': {'math': 80, 'science': 95}
}
all_grades = [grade for student_grades in student_grades.values() for grade in student_grades.values()]
print(all_grades) ## Output: [90, 85, 80, 95]
Conversion Strategy Decision Tree
flowchart TD
A[Data Source] --> B{Collection Type}
B --> |Dictionary| C[Keys/Values Conversion]
B --> |Set| D[Sorting/Filtering]
B --> |Tuple| E[Modification Needed]
C --> F[List Transformation]
D --> F
E --> F
Conversion Method |
Time Complexity |
Memory Efficiency |
Use Case |
list() |
O(n) |
Moderate |
General conversion |
List Comprehension |
O(n) |
High |
Filtered conversion |
sorted() |
O(n log n) |
Low |
Sorted list creation |
Advanced Conversion Techniques
Type-Safe Conversions
def safe_list_convert(data, data_type=int):
try:
return [data_type(item) for item in data]
except ValueError:
return []
## Example usage
mixed_data = ['1', '2', '3', 'four']
converted = safe_list_convert(mixed_data)
print(converted) ## Output: [1, 2, 3]
Best Practices
- Choose the most appropriate conversion method
- Consider performance for large datasets
- Handle potential type conversion errors
- Use list comprehensions for complex transformations
- Leverage built-in Python functions for efficient conversions