Python data types cheat sheet: Difference between revisions

From OpenHatch wiki
Content added Content deleted
imported>Mako
(generalizing the BPW cheatsheets for others to use)
 
imported>Hapytraylz
m (Accessing elements of a dictionary: her_dict undefined. Replaced with your_dict so that example Boolean relationships correct.)
 
(2 intermediate revisions by 2 users not shown)
Line 7: Line 7:
====Math: addition, subtraction, multiplication====
====Math: addition, subtraction, multiplication====


<b>addition</b>: 2 + 2<br />
'''addition''': 2 + 2<br />
<b>subtraction</b>: 0 - 2<br />
'''subtraction''': 0 - 2<br />
<b>multiplication</b>: 2 * 3<br />
'''multiplication''': 2 * 3<br />


====Math: division====
====Math: division====


>>> 4 / 2
<pre>
2
>>> 4 / 2
>>> 1 / 2
2
0
>>> 1 / 2
0
</pre>


* Integer division produces an integer. You need a number that knows about the decimal point to get a decimal out of division:
* Integer division produces an integer. You need a number that knows about the decimal point to get a decimal out of division:


>>> 1.0 / 2
<pre>
0.5
>>> 1.0 / 2
>>> float(1) / 2
0.5
0.5
>>> float(1) / 2
0.5
</pre>


====Types====
====Types====


>>> type(1)
<pre>
<type 'int'>
>>> type(1)
>>> type(1.0)
<type 'int'>
<type 'float'>
>>> type(1.0)
<type 'float'>
</pre>


==Strings==
==Strings==
Line 44: Line 38:
* Use triple-quotes (""") to create whitespace-preserving multi-line strings.
* Use triple-quotes (""") to create whitespace-preserving multi-line strings.


>>> "Hello"
<pre>
>>> "Hello"
'Hello'
'Hello'
</pre>


====String concatenation====
====String concatenation====


>>> "Hello" + "World"
<pre>
HelloWorld
>>> "Hello" + "World"
>>> "Hello" + "World" + 1
HelloWorld
Traceback (most recent call last):
>>> "Hello" + "World" + 1
File "<stdin>", line 1, in <module>
Traceback (most recent call last):
TypeError: cannot concatenate 'str' and 'int' objects
File "<stdin>", line 1, in <module>
>>> "Hello" + "World" + str(1)
TypeError: cannot concatenate 'str' and 'int' objects
'HelloWorld1'
>>> "Hello" + "World" + str(1)
'HelloWorld1'
</pre>


====Printing strings====
====Printing strings====


>>> print("Hello" + "World")
<pre>
HelloWorld
>>> print("Hello" + "World")
HelloWorld
</pre>


>>> name = "Jessica"
<pre>
>>> name = "Jessica"
>>> print("Hello " + name)
>>> print("Hello " + name)
Hello Jessica
Hello Jessica
</pre>


>>> print("""In 2009,
<pre>
... The monetary component of the Nobel Prize
>>> print("""In 2009,
... The monetary component of the Nobel Prize
... was US $1.4 million.""")
In 2009,
... was US $1.4 million.""")
The monetary component of the Nobel Prize
In 2009,
was US $1.4 million.
The monetary component of the Nobel Prize
was US $1.4 million.
</pre>


====Types====
====Types====


>>> type("Hello")
<pre>
<type 'str'>
>>> type("Hello")
<type 'str'>
</pre>


==Booleans==
==Booleans==
Line 98: Line 80:
====Containment with 'in' and 'not in'====
====Containment with 'in' and 'not in'====


>>> "H" in "Hello"
<pre>
True
>>> "H" in "Hello"
>>> "a" not in ["a", "b", "c"]
True
False
>>> "a" not in ["a", "b", "c"]
False
</pre>


====Equality====
====Equality====
Line 111: Line 91:
* <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class.
* <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class.


>>> 0 == 0
<pre>
True
>>> 0 == 0
>>> 0 == 1
True
False
>>> 0 == 1
False
</pre>


"a" != "a"
<pre>
"a" != "a"
</pre>


"a" != "A"
<pre>
"a" != "A"
</pre>


====Use with if/else blocks====
====Use with if/else blocks====
Line 130: Line 104:
* When Python encounters the <code>if</code> keyword, it evaluates the expression following the keyword and before the colon. If that expression is <code>True</code>, Python executes the code in the indented code block under the if line. If that expression is <code>False</code>, Python skips over the code block.
* When Python encounters the <code>if</code> keyword, it evaluates the expression following the keyword and before the colon. If that expression is <code>True</code>, Python executes the code in the indented code block under the if line. If that expression is <code>False</code>, Python skips over the code block.


temperature = 32
<pre>
temperature = 32
if temperature > 60 and temperature < 75:
print("It's nice and cozy in here!")
if temperature > 60 and temperature < 75:
else:
print("It's nice and cozy in here!")
print("Too extreme for me.")
else:
print("Too extreme for me.")
</pre>


====Types====
====Types====


>>> type(True)
<pre>
<type 'bool'>
>>> type(True)
>>> type(False)
<type 'bool'>
<type 'bool'>
>>> type(False)
<type 'bool'>
</pre>


==Lists==
==Lists==
Line 154: Line 124:
====List initialization====
====List initialization====


>>> my_list = []
<pre>
>>> my_list = []
>>> my_list
[]
>>> my_list
>>> your_list = ["a", "b", "c", 1, 2, 3]
[]
>>> your_list = ["a", "b", "c", 1, 2, 3]
>>> your_list
['a', 'b', 'c', 1, 2, 3]
>>> your_list
['a', 'b', 'c', 1, 2, 3]
</pre>


====Access and adding elements to a list====
====Access and adding elements to a list====


>>> len(my_list)
<pre>
0
>>> len(my_list)
>>> my_list[0]
0
Traceback (most recent call last):
>>> my_list[0]
File "<stdin>", line 1, in <module>
Traceback (most recent call last):
IndexError: list index out of range
File "<stdin>", line 1, in <module>
>>> my_list.append("Alice")
IndexError: list index out of range
>>> my_list.append("Alice")
>>> my_list
['Alice']
>>> my_list
>>> len(my_list)
['Alice']
1
>>> len(my_list)
>>> my_list[0]
1
'Alice'
>>> my_list[0]
>>> my_list.insert(0, "Amy")
'Alice'
>>> my_list.insert(0, "Amy")
>>> my_list
['Amy', 'Alice']
>>> my_list
['Amy', 'Alice']
</pre>


>>> my_list = ['Amy', 'Alice']
<pre>
>>> my_list = ['Amy', 'Alice']
>>> 'Amy' in my_list
True
>>> 'Amy' in my_list
>>> 'Bob' in my_list
True
False
>>> 'Bob' in my_list
False
</pre>


====Changing elements in a list====
====Changing elements in a list====


>>> your_list = []
<pre>
>>> your_list = []
>>> your_list.append("apples")
>>> your_list.append("apples")
>>> your_list[0]
'apples'
>>> your_list[0]
>>> your_list[0] = "bananas"
'apples'
>>> your_list[0] = "bananas"
>>> your_list
['bananas']
>>> your_list
['bananas']
</pre>


====Slicing lists====
====Slicing lists====


>>> her_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
<pre>
>>> her_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> her_list[0]
'a'
>>> her_list[0]
>>> her_list[0:3]
'a'
['a', 'b', 'c']
>>> her_list[0:3]
>>> her_list[:3]
['a', 'b', 'c']
['a', 'b', 'c']
>>> her_list[:3]
>>> her_list[-1]
['a', 'b', 'c']
'h'
>>> her_list[-1]
>>> her_list[5:]
'h'
['f', 'g', 'h']
>>> her_list[5:]
>>> her_list[:]
['f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> her_list[:]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
</pre>


====Strings are a lot like lists====
====Strings are a lot like lists====


>>> my_string = "Hello World"
<pre>
>>> my_string = "Hello World"
>>> my_string[0]
'H'
>>> my_string[0]
>>> my_string[:5]
'H'
'Hello'
>>> my_string[:5]
>>> my_string[6:]
'Hello'
'World'
>>> my_string[6:]
>>> my_string = my_string[:6] + "Jessica"
'World'
>>> my_string = my_string[:6] + "Jessica"
>>> my_string
'Hello Jessica'
>>> my_string
'Hello Jessica'
</pre>


* One big way in which strings are different from lists is that lists are mutable (you can change them), and strings are immutable (you can't change them). To "change" a string you have to make a copy:
* One big way in which strings are different from lists is that lists are mutable (you can change them), and strings are immutable (you can't change them). To "change" a string you have to make a copy:


>>> h = "Hello"
<pre>
>>> h = "Hello"
>>> h[0] = "J"
Traceback (most recent call last):
>>> h[0] = "J"
File "<stdin>", line 1, in <module>
Traceback (most recent call last):
TypeError: 'str' object does not support item assignment
File "<stdin>", line 1, in <module>
>>> h = "J" + h[1:]
TypeError: 'str' object does not support item assignment
>>> h = "J" + h[1:]
>>> h
'Jello'
>>> h
'Jello'
</pre>


====Types====
====Types====


>>> type(my_list)
<pre>
<type 'list'>
>>> type(my_list)
<type 'list'>
</pre>


==Dictionaries==
==Dictionaries==
Line 265: Line 219:
====Initialization====
====Initialization====


>>> my_dict = {}
<pre>
>>> my_dict = {}
>>> my_dict
{}
>>> my_dict
>>> your_dict = {"Alice" : "chocolate", "Bob" : "strawberry", "Cara" : "mint chip"}
{}
>>> your_dict
>>> your_dict = {"Alice" : "chocolate", "Bob" : "strawberry", "Cara" : "mint chip"}
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Alice': 'chocolate'}
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Alice': 'chocolate'}
</pre>


====Adding elements to a dictionary====
====Adding elements to a dictionary====


>>> your_dict["Dora"] = "vanilla"
<pre>
>>> your_dict["Dora"] = "vanilla"
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'chocolate'}
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'chocolate'}
</pre>


====Accessing elements of a dictionary====
====Accessing elements of a dictionary====


>>> your_dict["Alice"]
<pre>
'chocolate'
>>> your_dict["Alice"]
>>> your_dict.get("Alice")
'chocolate'
'chocolate'
>>> your_dict.get("Alice")
'chocolate'
</pre>


>>> your_dict["Eve"]
<pre>
Traceback (most recent call last):
>>> your_dict["Eve"]
File "<stdin>", line 1, in <module>
Traceback (most recent call last):
KeyError: 'Eve'
File "<stdin>", line 1, in <module>
>>> "Eve" in your_dict
KeyError: 'Eve'
False
>>> "Eve" in her_dict
>>> "Alice" in your_dict
False
True
>>> "Alice" in her_dict
>>> your_dict.get("Eve")
True
>>> your_dict.get("Eve")
>>> person = your_dict.get("Eve")
>>> person = your_dict.get("Eve")
>>> print(person)
None
>>> print(person)
>>> print(type(person))
None
<type 'NoneType'>
>>> print(type(person))
>>> your_dict.get("Alice")
<type 'NoneType'>
'chocolate'
>>> your_dict.get("Alice")
'coconut'
</pre>


====Changing elements of a dictionary====
====Changing elements of a dictionary====


>>> your_dict["Alice"] = "coconut"
<pre>
>>> your_dict["Alice"] = "coconut"
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'coconut'}
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'coconut'}
</pre>


====Types====
====Types====


>>> type(my_dict)
<pre>
<type 'dict'>
>>> type(my_dict)
<type 'dict'>
</pre>

Latest revision as of 19:53, 15 November 2014

Numbers: integers and floats

  • Integers don't have a decimal place.
  • Floats have a decimal place.
  • Math mostly works the way it does on a calculator, and you can use parentheses to override the order of operations.

Math: addition, subtraction, multiplication

addition: 2 + 2
subtraction: 0 - 2
multiplication: 2 * 3

Math: division

>>> 4 / 2
2
>>> 1 / 2
0
  • Integer division produces an integer. You need a number that knows about the decimal point to get a decimal out of division:
>>> 1.0 / 2
0.5
>>> float(1) / 2
0.5

Types

>>> type(1)
<type 'int'>
>>> type(1.0)
<type 'float'>

Strings

  • Strings are bits of text, and contain characters like numbers, letters, whitespace, and punctuation.
  • String are surrounded by quotes.
  • Use triple-quotes (""") to create whitespace-preserving multi-line strings.
>>> "Hello"
'Hello'

String concatenation

>>> "Hello" + "World"
HelloWorld
>>> "Hello" + "World" + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> "Hello" + "World" + str(1)
'HelloWorld1'

Printing strings

>>> print("Hello" + "World")
HelloWorld
>>> name = "Jessica"
>>> print("Hello " + name)
Hello Jessica
>>> print("""In 2009,
...     The monetary component of the Nobel Prize
...         was US $1.4 million.""")
In 2009,
    The monetary component of the Nobel Prize
        was US $1.4 million.

Types

>>> type("Hello")
<type 'str'>

Booleans

  • There are two booleans, True and False.
  • Use booleans to make decisions.

Containment with 'in' and 'not in'

>>> "H" in "Hello"
True
>>> "a" not in ["a", "b", "c"]
False

Equality

  • == tests for equality
  • != tests for inequality
  • <, <=, >, and >= have the same meaning as in math class.
>>> 0 == 0
True
>>> 0 == 1
False
"a" != "a"
"a" != "A"

Use with if/else blocks

  • When Python encounters the if keyword, it evaluates the expression following the keyword and before the colon. If that expression is True, Python executes the code in the indented code block under the if line. If that expression is False, Python skips over the code block.
temperature = 32
if temperature > 60 and temperature < 75:
    print("It's nice and cozy in here!")
else:
    print("Too extreme for me.")

Types

>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>

Lists

  • Use lists to store data where order matters.
  • Lists are indexed starting with 0.

List initialization

>>> my_list = []
>>> my_list
[]
>>> your_list = ["a", "b", "c", 1, 2, 3]
>>> your_list
['a', 'b', 'c', 1, 2, 3]

Access and adding elements to a list

>>> len(my_list)
0
>>> my_list[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> my_list.append("Alice")
>>> my_list
['Alice']
>>> len(my_list)
1
>>> my_list[0]
'Alice'
>>> my_list.insert(0, "Amy")
>>> my_list
['Amy', 'Alice']
>>> my_list = ['Amy', 'Alice']
>>> 'Amy' in my_list
True
>>> 'Bob' in my_list
False

Changing elements in a list

>>> your_list = []
>>> your_list.append("apples")
>>> your_list[0]
'apples'
>>> your_list[0] = "bananas"
>>> your_list
['bananas']

Slicing lists

>>> her_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> her_list[0]
'a'
>>> her_list[0:3]
['a', 'b', 'c']
>>> her_list[:3]
['a', 'b', 'c']
>>> her_list[-1]
'h'
>>> her_list[5:]
['f', 'g', 'h']
>>> her_list[:]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Strings are a lot like lists

>>> my_string = "Hello World"
>>> my_string[0]
'H'
>>> my_string[:5]
'Hello'
>>> my_string[6:]
'World'
>>> my_string = my_string[:6] + "Jessica"
>>> my_string
'Hello Jessica'
  • One big way in which strings are different from lists is that lists are mutable (you can change them), and strings are immutable (you can't change them). To "change" a string you have to make a copy:
>>> h = "Hello"
>>> h[0] = "J"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> h = "J" + h[1:]
>>> h
'Jello'

Types

>>> type(my_list)
<type 'list'>

Dictionaries

  • Use dictionaries to store key/value pairs.
  • Dictionaries do not guarantee ordering.
  • A given key can only have one value, but multiple keys can have the same value.

Initialization

>>> my_dict = {}
>>> my_dict
{}
>>> your_dict = {"Alice" : "chocolate", "Bob" : "strawberry", "Cara" : "mint chip"}
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Alice': 'chocolate'}

Adding elements to a dictionary

>>> your_dict["Dora"] = "vanilla"
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'chocolate'}

Accessing elements of a dictionary

>>> your_dict["Alice"]
'chocolate'
>>> your_dict.get("Alice")
'chocolate'
>>> your_dict["Eve"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Eve'
>>> "Eve" in your_dict
False
>>> "Alice" in your_dict
True
>>> your_dict.get("Eve")
>>> person = your_dict.get("Eve")
>>> print(person)
None
>>> print(type(person))
<type 'NoneType'>
>>> your_dict.get("Alice")
'chocolate'

Changing elements of a dictionary

>>> your_dict["Alice"] = "coconut"
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'coconut'}

Types

>>> type(my_dict)
<type 'dict'>