-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy path08_comprehensions.py
More file actions
42 lines (30 loc) · 1.07 KB
/
08_comprehensions.py
File metadata and controls
42 lines (30 loc) · 1.07 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
"""
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 = []
for x in range(5):
y.append(x+1)
print(y)
# Write a list comprehension to produce the cubes of the numbers 0-9:
# [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
y = [x**3 for x 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 = []
for x in a:
y.append(x.upper())
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 = []
print(y)