'Python List Comprehension' is a concise way to create a list. It is a single line of code that can replace a loop, making your code more pythonic and easier to read. List comprehension allows you to create a list by iterating over an iterable object, such as a list, tuple, or string, and applying an operation to each element. In this blog post, we will dive into the basics of list comprehension and explore how it can be used to improve your coding style.
When I started working with Python, my typical workflow to create a new list from the values of an existing list would look like the following.
- An existing list exists
- Create a new empty list
- Use a
appendmethod to add 'some' items from the existing list to the new list.
numbers = [1,3,4,7,9,12,15,20,21,26] even_numbers =  for number in numbers: if number % 2 == 0: # even numbers are exactly divisible by 2 that means remainder will be 0 even_numbers.append(number) print(even_numbers) #output [4, 12, 20, 26]
Python Modulo Operator
% returns the remainder of dividing the left-hand operand by the right-hand operand. It's used to get the remainder of a division. So,
10 % 3 would give the result of
If I were to re-write the same code in the Pythonic way using list comprehension, it would look like the following. You can do all the
for loop and
conditionals with just one line of code.
numbers = [1,3,4,7,9,12,15,20,21,26] even_numbers = [number for number in numbers if number %2 == 0] print(even_numbers) #output [4, 12, 20, 26]
newlist = [expression for item in iterable if condition == True]
Let's look at another example with multiple
conditionals. Let's say we want to find all the colours that have the letters
o in them but not the letter
The code would look like the following where we can group all the conditionals inside a parenthesis.
colours = ['red', 'blue', 'green', 'yello', 'purple', 'orange'] specific_colour = [colour for colour in colours if ('a' and 'o' in colour and 'l' not in colour)] print(specific_colour) #output ['orange']
Thank you for reading my blog post on 'Python List Comprehension' and I hope you found the information useful and that it gave you some new insights or ideas to consider.
If you have any thoughts or questions about the topic, please feel free to leave a comment or send me a message. I would love to continue the discussion and hear your perspective. Again, thank you for taking the time to read my post and for supporting my writing.