Arithmetic is relatively standard.
2
3
0.5
16
The modulo operator in python is %, which compares to %% in R. Integer division uses // in python and %/% in R.
1
2
50
2
5
10
You can use single or double quotes, but inner quotes need to differ from outter quotes.
'single quotes'
'double quotes'
wrap lot's of other quotes
He said, "Hello."
'hello'
hello
> num = 12
+ name = 'Sam'
+ print('My number is: {one}, and my name is: {two}'.
+ format(one=num,two=name))My number is: 12, and my name is: Sam
My number is: 12, and my name is: Sam
Unlike in R, python uses zero indexing. In R, selecting the first 3 would be 1:3. In python it is 0:3 (0,1, and 2. Up to but not including 3).
'o'
'o'
'abcdefghijk'
'abc'
'def'
A sequence of elements in square brackets, separated by commas.
[1, 2, 3]
['hi', 1, [1, 2]]
['a', 'b', 'c', 'd']
'a'
['b', 'c']
['b', 'c', 'd']
['a']
You can also use assignment
['NEW', 'b', 'c', 'd']
[4, 5, ['target']]
['target']
'target'
2
1
key:value pair mappings
{'key1': 'item1', 'key2': 'item2'}
'item1'
2
2
Booleans have a value of TRUE or FALSE.
Similar to lists, but in parentheses and are immutable.
1
Error in py_call_impl(callable, dots$args, dots$keywords): TypeError: 'tuple' object does not support item assignment
Detailed traceback:
File "<string>", line 1, in <module>
False
True
True
True
True
True
False
Python doesn’t use brackets to separate block of code execution statements (like in R) it uses whitespace.
Yep!
yep!
first
It will stop executing when the first condition is met.
> if 1 == 2:
+ print('first')
+ elif 3 == 3:
+ print('second')
+ elif 4 == 4:
+ print('middle')
+ else:
+ print('Last')second
item is a temporary variable name.
1
2
3
4
5
Yep
Yep
Yep
Yep
Yep
2
4
6
8
10
[1, 2, 3, 4, 5]
range(0, 5)
0
1
2
3
4
[0, 1, 2, 3, 4]
List comprehension is an efficient way to perform a looping operation on a set. It can be accomplished in one line.
[1, 4, 9, 16]
Instead of a loop you can use this format: new_list = [expression for member in iterable]
[1, 4, 9, 16]
[1, 4, 9, 16]
hello
Hello Default Name
Hello Paul
> def my_func(param1='default'):
+ """
+ Docstring goes here.
+ Can go multiple lines
+ """
+ print(param1)default
new param
You can add a doc string inside a function. Then, just use <shift><tab> after writing the function and it will be displayed.
4
You can create an anonymous function with lambda.
4
<function <lambda> at 0x000000002BE69678>
You can evaluate a function on each element of a list using map. It is similar to R’s map function from purrr.
<map object at 0x000000002BD27188>
[2, 4, 6, 8, 10]
Mapping an anonymous function using lambda.
[2, 4, 6, 8, 10]
You can also filter across a list.
<filter object at 0x000000002BD27748>
[2, 4]
You can retrieve a list of available methods by using <tab> after typing a function name follow by a period.
'hello my name is sam'
'HELLO MY NAME IS SAM'
You can also split a string. In R you can do the same with stringr::str_split().
['hello', 'my', 'name', 'is', 'Sam']
['Go Sports! ', 'Sports']
'Sports'
{'k1': 1, 'k2': 2}
dict_keys(['k1', 'k2'])
dict_items([('k1', 1), ('k2', 2)])
dict_values([1, 2])
.pop() will remove the last element, and the change is permanent.
3
[1, 2]
1
False
True
(1, 2)
1
(1, 2)
(3, 4)
(5, 6)
1
3
5
1
2
3
4
5
6
2401
s = "Hi there Sam!"['Hi', 'there', 'Sam!']
.format() to print the following string:> planet = "Earth"
+ diameter = 12742
+ print('The diameter of {one} is {two} kilometers.'.
+ format(one=planet,two=diameter))The diameter of Earth is 12742 kilometers.
'hello'
> d = {'k1':[1,2,3,{'tricky':['oh','man',
+ 'inception',{'target':[1,2,3,'hello']}]}]}
+
+ d['k1'][3]['tricky'][3]['target'][3]'hello'
'domain.com'
True
> def countDog(st):
+ count = 0
+ for word in st.lower().split():
+ if word == 'dog':
+ count += 1
+ return count
+
+ countDog('This dog runs faster than the other dog dude!')2
filter() function to filter out words from a list that don’t start with the letter ‘s’. For example:['soup', 'salad']
> def caught_speeding(speed, is_birthday):
+
+ if is_birthday:
+ speeding = speed - 5
+ else:
+ speeding = speed
+
+ if speeding > 80:
+ return 'Big Ticket'
+ elif speeding > 60:
+ return 'Small Ticket'
+ else:
+ return 'No Ticket'
+
+
+ caught_speeding(81,True)'Small Ticket'
'Big Ticket'