Skip to content

Instantly share code, notes, and snippets.

@fabsta
Created August 28, 2016 20:27
Show Gist options
  • Save fabsta/80ca194b513f3bd19673b161ceae3ba7 to your computer and use it in GitHub Desktop.
Save fabsta/80ca194b513f3bd19673b161ceae3ba7 to your computer and use it in GitHub Desktop.

FOR LOOPS AND WHILE LOOPS

range returns a list of integers

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'

for loop (not recommended)

fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
    print fruits[i].upper()

alternative for loop (recommended style)

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

iterate through two things at once (using tuple unpacking)

family = {'dad':'homer', 'mom':'marge', 'size':6}
for key, value in family.items():
    print key, value

use enumerate if you need to access the index value within the loop

for index, fruit in enumerate(fruits):
    print index, fruit

for/else loop

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"

while loop

count = 0
while count < 5:
    print "This will print 5 times"
    count += 1      # equivalent to 'count = count + 1'

COMPREHENSIONS

for loop to create a list of cubes

nums = [1, 2, 3, 4, 5]
cubes = []
for num in nums:
    cubes.append(num**3)

equivalent list comprehension

cubes = [num**3 for num in nums]    # [1, 8, 27, 64, 125]

for loop to create a list of cubes of even numbers

cubes_of_even = []
for num in nums:
    if num % 2 == 0:
        cubes_of_even.append(num**3)

equivalent list comprehension

syntax: [expression for variable in iterable if condition]

cubes_of_even = [num**3 for num in nums if num % 2 == 0]    # [8, 64]

for loop to cube even numbers and square odd numbers

cubes_and_squares = []
for num in nums:
    if num % 2 == 0:
        cubes_and_squares.append(num**3)
    else:
        cubes_and_squares.append(num**2)

equivalent list comprehension (using a ternary expression)

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]

for loop to flatten a 2d-matrix

matrix = [[1, 2], [3, 4]]
items = []
for row in matrix:
    for item in row:
        items.append(item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment