Skip to content

Commit 3960872

Browse files
authored
Merge pull request #6 from ew4321/master
Create sample file for list comprehensions
2 parents 7f0c574 + a1d9f96 commit 3960872

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

samplelistcomprehension.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Hi! Welcome to this mini tutorial on using list comprehensions in Python!
2+
# Check out samplelists.py if you need help with lists.
3+
4+
# Starting off with list comprehensions!
5+
# Syntax used to make an ordinary list:
6+
my_list = ["apple", "banana", "pear", "peach"]
7+
8+
# To concisely make a new list of elements, use a list comprehension:
9+
list_comp = [num for num in range(10)] # Notice how square brackets are
10+
# used to create a list.
11+
print list_comp
12+
13+
# List comprehension syntax can be understood as so:
14+
# [num for num in range(5)]
15+
# Make a new num for each num in given range
16+
17+
# The first expression (before the "for" keyword) can be altered to satisfy a
18+
# given condition over an iterable.
19+
doubled_list_comp = [num * 2 for num in list_comp]
20+
print doubled_list_comp
21+
22+
# Furthermore, "if" statements can be used in list comprehensions as well.
23+
even_num_list_comp = [num for num in list_comp if num % 2 == 0]
24+
print even_num_list_comp

0 commit comments

Comments
 (0)