Srikanth parikibanda’s Post

PYTHON JOURNEY - Day 47 / 50..!! TOPIC – List Comprehensions Today I explored one of Python’s most "elegant" features — List Comprehensions. It’s a shorthand way to create new lists based on existing ones, turning 4 lines of code into just 1! 1. The Traditional Way vs. Comprehension Normally, to create a list of squares, you’d need a for loop and .append(). With comprehension, it’s a single line! Python # Traditional Way nums = [1, 2, 3] squares = [] for x in nums: squares.append(x * x) # List Comprehension (The Pythonic Way) squares = [x * x for x in nums] print(squares) # Output: [1, 4, 9] 2. Adding a Condition (The if part) You can filter items while creating the list. Python prices = [10, 55, 80, 25, 100] # Only keep prices over 50 expensive = [p for p in prices if p > 50] print(expensive) # Output: [55, 80, 100] 3. String Manipulation It works perfectly for transforming text data too. Python names = ["srikanth", "python", "dev"] capitalized = [n.capitalize() for n in names] print(capitalized) # Output: ['Srikanth', 'Python', 'Dev'] Why Use List Comprehensions? Readability: Once you learn the syntax, it's much easier to read at a glance. Performance: They are generally faster than standard for-loops for creating lists. Professional: It is a hallmark of "Pythonic" code—showing you really know the language! Mini Task Write a program that: Creates a list of numbers from 1 to 10. Uses List Comprehension to create a new list containing only the even numbers. Prints the resulting list. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories