-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy path08_comprehensions.py
More file actions
43 lines (30 loc) · 1.16 KB
/
08_comprehensions.py
File metadata and controls
43 lines (30 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""
List comprehensions are one cool and unique feature of Python.
They essentially act as a terse and concise way of initializing
and populating a list given some expression that specifies how
the list should be populated.
Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
for more info regarding list comprehensions.
"""
# Write a list comprehension to produce the array [1, 2, 3, 4, 5]
y = [num for num in range(1, 6)]
print(y)
y1 = []
for num in range(1, 6):
y1.append(num)
print(y1)
# Write a list comprehension to produce the cubes of the numbers 0-9:
# [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
y = [num**3 for num in range(10)]
print(y)
# Write a list comprehension to produce the uppercase version of all the
# elements in array a. Hint: "foo".upper() is "FOO".
a = ["foo", "bar", "baz"]
y = [word.upper() for word in a]
print(y)
# Use a list comprehension to create a list containing only the _even_ elements
# the user entered into list x.
x = input("Enter comma-separated numbers: ").split(',')
# What do you need between the square brackets to make it work?
y = [num for num in x if int(num) % 2 == 0]
print(y)