Python Cheat Sheet

From Notepedia
Jump to: navigation, search

Syntax

CheatSheet: http://learnpythonthehardway.org/book/ex37.html

Add an element to an array
hobbies = [] 
hobbies.append("Bikes")
hobbies.append("Beer")

Ranges:

range(20) # prints from 0 to 19
range(1, 20) # prints from 1 to 19
range(1, 20, 2) # prints every second number between 1 and 19


For loop

word = 'Hello'
for i in word:
	print i

Not in

Will check if a scalar is in an array

empty = []
d = 10
if d not in empty:
	empty.append(d)

List Comprehension

Creates a list of every number between 1 and 10, that is even, and then squares them

l = [i ** 2 for i in range(1, 11) if i % 2 == 0]

List slicing

l = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print l[2:9:2]
l[start:end:stride]

to_five = ['A', 'B', 'C', 'D', 'E']

print to_five[3:]
# prints ['D', 'E'] 

print to_five[:2]
# prints ['A', 'B']

print to_five[::2]
# print ['A', 'C', 'E']

Reverse

print letters[::-1]


Lambda (Annon Functions)

languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == "Python", languages)