Python Fundamentals


Creating Lists


Using for loops:

squares = [] #Step 1: Create an empty list
for i in range(10):#Step 2: Iterate
	squares.append(i*i) #Step 3: Append to empty list

Using map() objects: Pass a function and an iterable to map().

transactions = [1.09,23.56,57.84]
TAX_RATE = 0.08
def get_price_with_tax(txn):
	return txn * (1+TAX_RATE)

final_prices = map(get_price_with_tax, transactions)
list(final_prices) # Will be a list

Using List Comprehensions: Here, we define the list and its contents at the same time. Syntax is new_list = [expression **for** member **in** iterable]

#Example 1
squares = [i*i for i in range(10)]
#Example 2
transactions = [1.09,23.56,57.84]
TAX_RATE = 0.08
def get_price_with_tax(txn):
	return txn * (1+TAX_RATE)

# Using list comprehension, we will get a list, instead of a map object
final_prices = [get_price_with_tax(i) for i in transactions]

Useful List Methods