0% found this document useful (0 votes)
15 views5 pages

Comprehensions List and Dict Question PDF

The document contains a series of list and dictionary comprehension problems with solutions in Python. It includes tasks such as generating squares, filtering numbers, creating tuples, and mapping values to their squares. Additionally, it covers converting lists to dictionaries, counting character frequencies, and grouping numbers into categories.

Uploaded by

vigneshone998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views5 pages

Comprehensions List and Dict Question PDF

The document contains a series of list and dictionary comprehension problems with solutions in Python. It includes tasks such as generating squares, filtering numbers, creating tuples, and mapping values to their squares. Additionally, it covers converting lists to dictionaries, counting character frequencies, and grouping numbers into categories.

Uploaded by

vigneshone998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Intermediate List and Dictionary Comprehension Problems:

List Comprehension Questions


# 1. Write a list comprehension to generate a list of squares
of numbers from 1 to 10.
squares = [x**2 for x in range(1, 11)]
print("Squares of numbers from 1 to 10:", squares)

# 2. Create a list comprehension that filters out even numbers


from a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = [x for x in numbers if x % 2 != 0]
print("Odd numbers from the list:", odd_numbers)

# 3. How would you create a list of tuples (x, x^2) for


numbers from 1 to 5?
tuples = [(x, x**2) for x in range(1, 6)]
print("List of tuples (x, x^2) for numbers from 1 to 5:",
tuples)

# 4. Generate a list of only the vowels from the string "list


comprehension is powerful".
string = "list comprehension is powerful"
vowels = [char for char in string if char in 'aeiou']
print("Vowels from the string:", vowels)

# 5. Write a nested list comprehension to create a 3x3 matrix


(list of lists) filled with zeros.
matrix = [[0 for _ in range(3)] for _ in range(3)]
print("3x3 Matrix filled with zeros:", matrix)

# 6. Convert a list of Celsius temperatures [0, 10, 20, 30] to


Fahrenheit using a list comprehension.
celsius = [0, 10, 20, 30]
fahrenheit = [(x * 9/5) + 32 for x in celsius]
print("Celsius to Fahrenheit:", fahrenheit)
# 7. Create a flattened list from a nested list [[1, 2], [3,
4], [5, 6]] using a list comprehension.
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in nested_list for item in
sublist]
print("Flattened list from nested list:", flattened)

# 8. Write a list comprehension to reverse each string in the


list ['apple', 'banana', 'cherry'].
words = ['apple', 'banana', 'cherry']
reversed_strings = [word[::-1] for word in words]
print("Reversed strings:", reversed_strings)

# 9. Generate a list of prime numbers between 1 and 20 using a


list comprehension.
primes = [x for x in range(2, 21) if all(x % i != 0 for i in
range(2, int(x**0.5) + 1))]
print("Prime numbers between 1 and 20:", primes)

# 10. Write a list comprehension to extract all numbers


divisible by both 3 and 5 from a range of 1 to 100.
divisible_by_3_and_5 = [x for x in range(1, 101) if x % 3 == 0
and x % 5 == 0]
print("Numbers divisible by both 3 and 5 between 1 and 100:",
divisible_by_3_and_5)

# 11. Use a conditional list comprehension to replace all


negative numbers in [-2, -1, 0, 1, 2] with 0.
numbers = [-2, -1, 0, 1, 2]
non_negative = [x if x >= 0 else 0 for x in numbers]
print("Replacing negative numbers with 0:", non_negative)

# 12. Generate a list of all uppercase letters in the string


"Hello World!" using a list comprehension.
string = "Hello World!"
uppercase_letters = [char for char in string if
char.isupper()]
print("Uppercase letters from the string:", uppercase_letters)

# 13. Create a list of squares of even numbers from a list [1,


2, 3, 4, 5, 6, 7, 8, 9, 10].
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = [x**2 for x in numbers if x % 2 == 0]
print("Squares of even numbers:", even_squares)
# 14. Use list comprehension to generate a list of 5 random
numbers between 1 and 10 (Hint: random.randint).
import random
random_numbers = [random.randint(1, 10) for _ in range(5)]
print("5 random numbers between 1 and 10:", random_numbers)

# 15. Write a list comprehension to generate a list of first


letters of each word in the sentence "Python is amazing".
sentence = "Python is amazing"
first_letters = [word[0] for word in sentence.split()]
print("First letters of each word in the sentence:",
first_letters)

Dictionary Comprehension Questions:


# 16. Create a dictionary comprehension to map numbers from 1
to 5 to their squares.
squares_dict = {x: x**2 for x in range(1, 6)}
print("Dictionary mapping numbers to their squares:",
squares_dict)

# 17. Convert a list ['name', 'age', 'gender'] and ['Alice',


25, 'Female'] into a dictionary using a dictionary
comprehension.
keys = ['name', 'age', 'gender']
values = ['Alice', 25, 'Female']
person_dict = {keys[i]: values[i] for i in range(len(keys))}
print("Converted list into dictionary:", person_dict)

# 18. Write a dictionary comprehension to count the frequency


of each character in the string "hello world".
string = "hello world"
char_frequency = {char: string.count(char) for char in string}
print("Character frequency in 'hello world':", char_frequency)

# 19. Use a dictionary comprehension to filter out key-value


pairs where the value is greater than 5 from the dictionary
{1: 10, 2: 5, 3: 7, 4: 3}.
sample_dict = {1: 10, 2: 5, 3: 7, 4: 3}
filtered_dict = {k: v for k, v in sample_dict.items() if v <=
5}
print("Filtered dictionary (value <= 5):", filtered_dict)
# 20. Create a dictionary where keys are numbers from 1 to 5
and values are their factorials using dictionary
comprehension.
from math import factorial
factorial_dict = {x: factorial(x) for x in range(1, 6)}
print("Dictionary of factorials:", factorial_dict)

# 21. Generate a dictionary of words and their lengths for the


sentence "Python dictionary comprehension is powerful".
sentence = "Python dictionary comprehension is powerful"
word_lengths = {word: len(word) for word in sentence.split()}
print("Dictionary of words and their lengths:", word_lengths)

# 22. Convert two lists ['a', 'b', 'c'] and [1, 2, 3] into a
dictionary using a dictionary comprehension.
keys = ['a', 'b', 'c']
values = [1, 2, 3]
converted_dict = {keys[i]: values[i] for i in
range(len(keys))}
print("Converted lists into dictionary:", converted_dict)

# 23. Reverse the key-value pairs of a dictionary {1: 'a', 2:


'b', 3: 'c'} using a dictionary comprehension.
sample_dict = {1: 'a', 2: 'b', 3: 'c'}
reversed_dict = {v: k for k, v in sample_dict.items()}
print("Reversed dictionary:", reversed_dict)

# 24. Write a dictionary comprehension to group numbers into


"even" and "odd" categories for the list [1, 2, 3, 4, 5, 6].
numbers = [1, 2, 3, 4, 5, 6]
grouped_numbers = {x: ("even" if x % 2 == 0 else "odd") for x
in numbers}
print("Grouped numbers as even or odd:", grouped_numbers)

# 25. Create a dictionary of squares of even numbers from 1 to


10 using dictionary comprehension.
even_squares_dict = {x: x**2 for x in range(1, 11) if x % 2 ==
0}
print("Dictionary of squares of even numbers:",
even_squares_dict)

# 26. Convert the nested dictionary {'a': 1, 'b': {'c': 2,


'd': 3}} into a flattened dictionary using dictionary
comprehension.
nested_dict = {'a': 1, 'b': {'c': 2, 'd': 3}}
flattened_dict = {f"{k1}.{k2}": v2 for k1, v in
nested_dict.items() for k2, v2 in (v.items() if isinstance(v,
dict) else [(k1, v)])}
print("Flattened dictionary:", flattened_dict)

# 27. Write a dictionary comprehension to filter out vowels


from a dictionary of letter frequencies {'a': 10, 'b': 20,
'e': 5, 'o': 8}.
letter_frequencies = {'a': 10, 'b': 20, 'e': 5, 'o': 8}
filtered_dict = {k: v for k, v in letter_frequencies.items()
if k not in 'aeiou'}
print("Filtered dictionary without vowels:", filtered_dict)

# 28. Given a list ['apple', 'banana', 'apple', 'cherry'],


create a dictionary to count the occurrences of each fruit.
fruits = ['apple', 'banana', 'apple', 'cherry']
fruit_count = {fruit: fruits.count(fruit) for fruit in
set(fruits)}
print("Fruit count dictionary:", fruit_count)

# 29. Transform a dictionary {'name': 'Alice', 'age': 25} into


another dictionary with values converted to uppercase strings
using a dictionary comprehension.
person_dict = {'name': 'Alice', 'age': 25}
uppercase_dict = {k: str(v).upper() for k, v in
person_dict.items()}
print("Uppercase dictionary:", uppercase_dict)

# 30. Create a dictionary from a list [1, 2, 3, 4, 5] where


keys are numbers and values are "even" or "odd" depending on
the number.
numbers = [1, 2, 3, 4, 5]
even_odd_dict = {x: ("even" if x % 2 == 0 else "odd") for x in
numbers}
print("Dictionary of 'even' and 'odd' values:", even_odd_dict)

You might also like