range(0, 3) # returns [0, 1, 2]: includes first value but excludes second value
range(3) # same thing: starting at zero is the default
range(0, 5, 2) # returns [0, 2, 4]: third argument specifies the 'stride'
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print fruits[i].upper()
for fruit in fruits:
print fruit.upper()
use xrange when iterating over a large sequence to avoid actually creating the integer list in memory
for i in xrange(10**6):
pass
family = {'dad':'homer', 'mom':'marge', 'size':6}
for key, value in family.items():
print key, value
for index, fruit in enumerate(fruits):
print index, fruit
for fruit in fruits:
if fruit == 'banana':
print "Found the banana!"
break # exit the loop and skip the 'else' block
else:
# this block executes ONLY if the for loop completes without hitting 'break'
print "Can't find the banana"
count = 0
while count < 5:
print "This will print 5 times"
count += 1 # equivalent to 'count = count + 1'
nums = [1, 2, 3, 4, 5]
cubes = []
for num in nums:
cubes.append(num**3)
cubes = [num**3 for num in nums] # [1, 8, 27, 64, 125]
cubes_of_even = []
for num in nums:
if num % 2 == 0:
cubes_of_even.append(num**3)
syntax: [expression for variable in iterable if condition]
cubes_of_even = [num**3 for num in nums if num % 2 == 0] # [8, 64]
cubes_and_squares = []
for num in nums:
if num % 2 == 0:
cubes_and_squares.append(num**3)
else:
cubes_and_squares.append(num**2)
syntax: [true_condition if condition else false_condition for variable in iterable]
cubes_and_squares = [num**3 if num % 2 == 0 else num**2 for num in nums] # [1, 8, 9, 64, 25]
matrix = [[1, 2], [3, 4]]
items = []
for row in matrix:
for item in row:
items.append(item)