Python List comprehensions
List comprehensions
You can use a loop to generate a list based on a range of numbers or on another list. This is a common operation, so python offers a more efficient way to do it. List comprehensions may look complicated at first: if so, use the for loop approach until you're ready to start using comprehensions.
To write a comprehension, define an expression for the values you want to store in the list. Then write a for loop to generate input values needed top make the list.
You can use a loop to generate a list based on a range of numbers or on another list. This is a common operation, so python offers a more efficient way to do it. List comprehensions may look complicated at first: if so, use the for loop approach until you're ready to start using comprehensions.
To write a comprehension, define an expression for the values you want to store in the list. Then write a for loop to generate input values needed top make the list.
#Using a loop to generate a list of square numbers squares = [] for x in range(1, 11): square = x**2 squares.append(square) #Using a comprehension to generate a list of square numbers squares = [x**2 for x in range(1, 11)] #Using a loop to convert a list of names to upper case names = ['kai', 'abe', 'ada', 'gus', 'zoe'] upper_names = [] for name in names: upper_names.append(name.upper()) #upper a comprehension to convert a list of names to upper case names = ['kai', 'abe', 'ada', 'gus', 'zoe'] upper_names = [name.upper() for name in names] print(upper_names)
No comments:
Post a Comment