top of page

25% Discount For All Pricing Plans "welcome"

Comprehension in Python

Comprehensions in Python

Comprehensions in Python are a concise and powerful way to create lists, sets, and dictionaries. They allow us to create these data structures in a single line of code, without the need for a loop. In this article, we will discuss comprehensions in Python in detail, along with examples.


List Comprehensions


List comprehensions are used to create new lists from an existing iterable object. The basic syntax for list comprehension is as follows:


new_list = [expression for item in iterable if condition]
  • The expression is the operation that will be performed on each item of the iterable.

  • The item is the variable that represents each element in the iterable.

  • The iterable is the object that we want to iterate over.

  • The condition is an optional statement that filters the elements in the iterable based on a certain condition.

Here's an example of a list comprehension that squares each number in a list:


numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares)

Output:


[1, 4, 9, 16, 25]

Here are a few more examples of list comprehensions in Python:


#Filtering strings by length:

words = ["apple", "banana", "cherry", "date", "elderberry", "fig"] short_words = [word for word in words if len(word) < 6] print(short_words)  
Output:
['apple', 'date', 'fig']
  



#Creating a list of tuples:
numbers = [1, 2, 3, 4, 5] pairs = [(num, num ** 2) for num in numbers] print(pairs)  
Output:
[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]  



#Flattening a list of lists:
nested_lists = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] flattened_list = [item for sublist in nested_lists for item in sublist] print(flattened_list)  
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]  



Creating a list of even numbers:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = [num for num in numbers if num % 2 == 0] print(even_numbers)  
Output:
[2, 4, 6, 8, 10]  



#Creating a list of the first letter of words in a list:
words = ["apple", "banana", "cherry", "date", "elderberry", "fig"] first_letters = [word[0] for word in words] print(first_letters)  
Output:
['a', 'b', 'c', 'd', 'e', 'f']  



#Converting a list of strings to uppercase:
words = ["apple", "banana", "cherry", "date", "elderberry", "fig"] uppercase_words = [word.upper() for word in words] print(uppercase_words)  
Output:
['APPLE', 'BANANA', 'CHERRY', 'DATE', 'ELDERBERRY', 'FIG']  

These are just a few examples of what you can do with list comprehensions in Python. The possibilities are endless!


Set Comprehensions

Set comprehensions are similar to list comprehensions, but they are used to create sets. The basic syntax for a set comprehension is as follows:


new_set = {expression for item in iterable if condition}

Here's an example of a set comprehension that creates a set of even numbers from a list:


numbers = [1, 2, 3, 4, 5]
even_numbers = {num for num in numbers if num % 2 == 0}
print(even_numbers)

Output:


{2, 4}

Sure, here are a few more examples of set comprehensions in Python:



#Creating a set of vowels in a string:
sentence = "The quick brown fox jumps over the lazy dog" vowels = {char.lower() for char in sentence if char.lower() in "aeiou"} print(vowels)  
Output:
{'e', 'u', 'i', 'a', 'o'}  



#Creating a set of unique words in a sentence:
sentence = "the quick brown fox jumps over the lazy dog" words = sentence.split() unique_words = {word.lower() for word in words} print(unique_words)  
Output:
{'brown', 'jumps', 'lazy', 'over', 'fox', 'dog', 'quick', 'the'}  



#Creating a set of common elements in two lists:
list1 = [1, 2, 3, 4, 5] list2 = [3, 4, 5, 6, 7] common_elements = {num for num in list1 if num in list2} print(common_elements)  
Output:
{3, 4, 5}  

These are just a few more examples of what you can do with set comprehensions in Python. The possibilities are truly endless!


Dictionary Comprehensions

Dictionary comprehensions are used to create dictionaries. The basic syntax for a dictionary comprehension is as follows:


new_dict = {key_expression: value_expression for item in iterable if condition}
  • The key_expression is the operation that will be performed on each item to create the key of the dictionary.

  • The value_expression is the operation that will be performed on each item to create the value of the dictionary.

  • The item is the variable that represents each element in the iterable.

  • The iterable is the object that we want to iterate over.

  • The condition is an optional statement that filters the elements in the iterable based on a certain condition.

Here's an example of a dictionary comprehension that creates a dictionary of squares:


numbers = [1, 2, 3, 4, 5]
squares = {num: num ** 2 for num in numbers}
print(squares)

Output:


{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Sure, here are a few more examples of dictionary comprehensions in Python:



#Creating a dictionary of word lengths:
words = ["apple", "banana", "cherry", "date", "elderberry", "fig"] word_lengths = {word: len(word) for word in words} print(word_lengths)  
Output:
{'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4, 'elderberry': 10, 'fig': 3} 
 



#Creating a dictionary of even numbers and their squares:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_squares = {num: num ** 2 for num in numbers if num % 2 == 0} print(even_squares)  
Output:
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}  



#Creating a dictionary of letter frequencies in a string:
sentence = "The quick brown fox jumps over the lazy dog" letter_frequencies = {char.lower(): sentence.count(char) for char in sentence if char.isalpha()} print(letter_frequencies)  
Output:
{'t': 2, 'h': 2, 'e': 3, 'q': 1, 'u': 2, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 2, 'o': 4, 'w': 1, 'n': 2, 'f': 1, 'x': 1, 'j': 1, 'm': 1, 'p': 1, 's': 1, 'v': 1, 'l': 1, 'a': 1, 'z': 1, 'y': 1, 'd': 1, 'g': 1}  



#Creating a dictionary of file extensions and their corresponding MIME types:
files = ["test.txt", "image.jpg", "document.pdf", "audio.mp3", "video.mp4"] extensions = {file.split(".")[1]: "text/plain" if file.endswith(".txt") else "image/jpeg" if file.endswith(".jpg") else "application/pdf" if file.endswith(".pdf") else "audio/mpeg" if file.endswith(".mp3") else "video/mp4" for file in files} print(extensions)  
Output:
{'txt': 'text/plain', 'jpg': 'image/jpeg', 'pdf': 'application/pdf', 'mp3': 'audio/mpeg', 'mp4': 'video/mp4'}  



#Creating a dictionary of the first letter of words in a list and their corresponding lengths:
words = ["apple", "banana", "cherry", "date", "elderberry", "fig"] first_letter_lengths = {word[0]: len(word) for word in words} print(first_letter_lengths)  
Output:
{'a': 5, 'b': 6, 'c': 6, 'd': 4, 'e': 10, 'f': 3}  



#Creating a dictionary of the number of occurrences of each character in a string:
sentence = "The quick brown fox jumps over the lazy dog" char_counts = {char: sentence.count(char) for char in sentence if char.isalpha()} print(char_counts)  
Output:
{'T': 1, 'h': 2, 'e': 3, 'q': 1, 'u': 2, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 2, 'o': 4, 'w': 1, 'n': 2, 'f': 1, 'x': 1, 'j': 1, 'm': 1, 'p': 1, 's': 1, 'v': 1, 'l': 1, 'a': 1, 'z': 1, 'y': 1, 'd': 1, 'g': 1, 't': 1} 
 



#Creating a dictionary of word frequencies in a sentence:
sentence = "the quick brown fox jumps over the lazy dog" words = sentence.split() word_freqs = {word: words.count(word) for word in words} print(word_freqs)  
Output:
{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}  

These are just a few more examples of what you can do with dictionary comprehensions in Python. The possibilities are truly endless!


Conclusion

Comprehensions in Python are a powerful and concise way to create lists, sets, and dictionaries. They allow us to create these data structures in a single line of code, without the need for a loop. By using comprehensions, we can write cleaner and more readable code.


Commentaires


Les commentaires ont été désactivés.
bottom of page