List Object basic
# Initialization
L = [‘Alpha’, ‘Beta’, ‘Gamma’]
# Append new item
L.append(‘Delta’)
# Remove item by index
L.pop(idx)
# Remove item by value
L.remove(‘Alpha’)
Walk through list items
# The code below can not be stupid more
for i in range(len(L)):
print(L[i])
# Typical for loop
for item in L:
print(item)
# Would like to have index as well
for idx, item in enumerate(L):
print(“{0}: {1}”.format(idx, item))
List comprehension
# Would like to extract 1st letter of each item inside and make a new list
# Regular for loop
L2 = []
for item in L:
L2.append(L[0])
# List Comprehension
L2 = [x[0] for x in L]
# Use primitive function ‘map’ instead
L2 = map(lambda x: x[0], L)
Similar primitive function beside 'map'
# Keep the item if internal function output True, otherwise drop the item. Notice that function filter return a list which filter out unsatisfied items and leave other items unchanged.
filter(lambda x: …, L)
# Output True only if internal function return True for each item
all(lambda x: …, L)
# Output True if any of the internal function return True
some(lambda x: …, L)