Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # FOR LOOPS AND WHILE LOOPS
- # range returns a list of integers
- ```python
- 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)
- ```python
- fruits = ['apple', 'banana', 'cherry']
- for i in range(len(fruits)):
- print fruits[i].upper()
- ```
- ## alternative for loop (recommended style)
- ```python
- for fruit in fruits:
- print fruit.upper()
- ```
- ## use xrange when iterating over a large sequence to avoid actually creating the integer list in memory
- ```python
- for i in xrange(10**6):
- pass
- ```
- ## iterate through two things at once (using tuple unpacking)
- ```python
- 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
- ```python
- for index, fruit in enumerate(fruits):
- print index, fruit
- ```
- ## for/else loop
- ```python
- 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
- ```python
- 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
- ```python
- nums = [1, 2, 3, 4, 5]
- cubes = []
- for num in nums:
- cubes.append(num**3)
- ```
- ### equivalent list comprehension
- ```python
- cubes = [num**3 for num in nums] # [1, 8, 27, 64, 125]
- ```
- ### for loop to create a list of cubes of even numbers
- ```python
- 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]
- ```python
- 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
- ```python
- 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]
- ```python
- 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
- ```python
- matrix = [[1, 2], [3, 4]]
- items = []
- for row in matrix:
- for item in row:
- items.append(item)
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement