List comprehensions
A list comprehension is a compact way to create a list from another collection in a single line. It is one of the most typical…
Learn to write shorter, more Pythonic code. In this lesson you will see list, dictionary and set comprehensions, lambda functions, sorting with key, and the map, filter, zip and enumerate functions. You will also learn when a comprehension is a good fit and when a regular loop is better, with practical exercises.
A list comprehension is a compact way to create a list from another collection in a single line. It is one of the most typical…
The same idea of list comprehensions works to create dictionaries and sets, by changing the brackets to braces.
A lambda function is a small, nameless function written on a single line. It is mostly used to pass it to another function, such…
Python includes functions that loop over collections and combine or transform them. They are very convenient, and they are often…
Comprehensions are a great tool, but they are not always the best option. The golden rule: code is read many more times than it…
Create a Python program that generates the squares of the first numbers with a list comprehension.
Create a Python program that keeps only the even numbers of a list using a comprehension with a condition.
Create a Python program that calculates the length of each word of a sentence with a list comprehension.
Create a Python program that replaces each number with a label depending on whether it is even or odd, using a comprehension with…
Create a Python program that builds a dictionary with a dictionary comprehension.
Create a Python program that sorts the words of a sentence in two different ways using the key parameter of sorted .
Create a Python program that finds the student with the highest grade using max with key .
Create a Python program that combines two lists element by element with zip .
Create a Python program that numbers a list of lines of text using enumerate .
Create a Python program that filters and transforms a list of numbers with filter and map .