Python List Tips and Tricks
Dil Raj Gurung
Data Engineer | Data Analyst | ETL/SQL Developer | Python | Finance | Retail | Healthcare | AWS | Snowflake | ML | Towards Data Science
As a Data Engineer, Python is everybody's everyday tool, and lists are among the most powerful structures. Here are some essential Python list tips and tricks that I find can simplify your code and make it more efficient! ??
1? List Comprehensions: A concise way to create lists. Instead of writing loops, try:
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, ...]
2? Filter Using Comprehensions: Combine filtering and list creation:
even_numbers = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, ...]
3? Flatten Nested Lists: Flatten lists in one line:
nested = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat = [num for sublist in nested for num in sublist]
# [1, 2, 3, 4, 5, 6, 7, 8]
4? Zip and Unzip Lists: Pair up list elements easily:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
paired = list(zip(list1, list2))
# [(1, 'a'), (2, 'b'), (3, 'c')]
5? Remove Duplicates: Quickly clean up your list:
unique_list = list(set([1, 2, 2, 3, 4, 4, 5]))
# [1, 2, 3, 4, 5]
Have any other cool Python list tips? Share below! ??
#Python #Programming #DataEngineering #DataScience #PythonTips #CodeOptimization #TechSkills #LearningPython #DeveloperLife