Syntax
List
theList = list() # new list
theList = [] # new list
theList[1] # access with index value 1, list is zero based
theList.append('a')
theList = [1, 2, 3]
moreList = theList[:]
moreList
[1, 2, 3]
theList.append(4)
theList
[1, 2, 3, 4]
moreList
[1, 2, 3]
moreList = theList.copy()
Dictionary
theDict = dict() # new dict
theDict = {} # new dict
theDict['y'] # access with key value 'y'
if 'curious' not in theDict:
...
for oneKey in theDict:
oneValue = theDict[oneKey]
Set
theSet = {1, 1, 2, 3} // create a new set with initial elements
theSet = set() // create an empty set
theSet.add(1)
print(sorted(theSet, key=len)) // sort the set by the len of the element
Yield -- Generator
theList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def createGroupThree(theList):
size = 3
tmpList = []
for oneItem in theList:
if size == len(tmpList):
yield tmpList
tmpList = []
else:
tmpList.append(oneItem)
yield tmpList
for oneThree in createGroupThree(theList):
print '--> ' + str(oneThree)
--> [1, 2, 3]
--> [5, 6, 7]
--> [9, 10]
In Python 3.3, yield from, to chain generators.
List Composition
ids = [oneRow['id'] for oneRow in destRows]
Chunk Composition from List
theList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[theList[i:i+3] for i in xrange(0, len(theList), 3)]
--> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
Join Number List as Comma Separated String
theList = [1, 2, 3]
','.join(map(str, theList))
-> '1,2,3'
Ternary Operator (since v2.5)
x = 3
message = 'hello' if x > 0 else 'world'
For Loop
In C/C++, if you want to a for loop in the form:
for (int i = 0; i < 10; i++){
}
In Python, you will need to write:
for i in range(0, 10):
. . . # i will from 0 .. 9
or in reverse order:
for i in reversed(range(1900, 2017)):
... 2016, 2015, etc.