Lesson 7
List Comprehensions
Build lists in a single elegant line
1What Are List Comprehensions?✨
List comprehensions are a concise way to create lists in Python. They let you build new lists by applying an expression to each item in an existing list. This makes your code cleaner and easier to read!
2Creating a Simple List🎯
You can create a new list of squares from an existing list of numbers using list comprehensions. Here's how:
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)3This code produces the output: [1, 4, 9, 16, 25]💡
4Filtering with List Comprehensions🚀
You can also filter items while creating a new list. For example, to get only even numbers from a list:
numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)5This will output: [2, 4, 6]🔍
6Nested List Comprehensions⭐
List comprehensions can be nested to handle more complex data structures. For example, if you have a list of lists, you can flatten it:
matrix = [[1, 2], [3, 4], [5, 6]]
flat_list = [num for row in matrix for num in row]
print(flat_list)7This results in: [1, 2, 3, 4, 5, 6]🧩
8Practice with List Comprehensions🎈
Try creating your own list comprehension! Make a list of the first ten cubes (numbers raised to the power of three):cubes = [n**3 for n in range(1, 11)]
print(cubes)This should give you: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
9Wrapping Up✨
List comprehensions are a powerful tool in Python that help you write cleaner code. Keep practicing, and you'll find them to be very useful in your coding projects!
🎯 Practice Challenges
Master List Comprehensions by completing all 3 difficulty levels
List Comprehensions - Easy Challenge
Start with the basics. Perfect for beginners!
List Comprehensions - Medium Challenge
Get more challenging. Build your confidence!
List Comprehensions - Hard Challenge
Master this concept. Prove your skills!
🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →
Ready to Master List Comprehensions? 🚀
Complete the challenges, take the quiz and keep your learning streak going!
Keep learning
- ← Previous lessonLesson 6: Data ProjectsBuild data-driven programs
- Next lesson →Lesson 8: Nested Data StructuresLists of dictionaries and beyond
- Grade 8 courseJavaScript Basics - Web ProgrammingJavaScript coding course for kids.
- Student ToolsFree calculators for studentsPercentage, fraction, ratio and marks calculators with steps.
- CBSEClass 7 CBSE & NCERT study materialMaths, Science and Computer chapters with solutions.
- Future SkillsExplore future skillsAI, robotics and new-age skills explained for students.