Everything in python is an object¶

Numbers, lists, strings, functions, modules, and everything else in python is an object. Even attributes and methods of an object are objects.

In python = is the assignment defining the right-hand side expression value to the name at the left

In [17]:
a=8
b=8
c="Hello"
d="Hello"

print(id(a))
print(id(b))
print(id(a))
print(id(b))

print(type(a))
print(type(c))
140730254386184
140730254386184
140730254386184
140730254386184
<class 'int'>
<class 'str'>
In [18]:
print(a.numerator)
print(a.imag)
8
0

In Python, everything is an object. An object has its own internal state. Some objects allow you to change their internal state and others don’t.

An object whose internal state can be changed is called a $mutable$ object, while an object whose internal state cannot be changed is called an $immutable$ object.

The following are examples of immutable objects:

  • Numbers (int, float, bool,…)
  • Strings
  • Tuples
  • Frozen sets

The following are examples of mutable objects:

  • Lists
  • Sets
  • Dictionaries

User-defined classes can be mutable or immutable, depending on whether their internal state can be changed or not

Valid Names for Variables and Object¶

A variable name may consist of alphanumeric characters (a-z, A-Z, 0-9) and the underscore symbol (_); a valid name cannot begin with a numerical value.

var: valid
_var2: valid
ApplePie_Yum_Yum: valid
2cool: invalid (begins with a numerical character)
I.am.the.best: invalid (contains .)

They also cannot conflict with character sequences that are reserved by the Python language. As such, the following cannot be used as variable names:

for, while, break, pass, continue
in, is, not
if, else, elif
def, class, return, yield, raises
import, from, as, with
try, except, finally

Avoid also to use class name as : list, int, float, complex, etc

Standards Object type¶

The are three family of standard object defined in the basic set of python

  • Basic Structure: single type object
  • iterables collection of object
    • -> ordered collection of objects : Sequence
    • -> unordered collection of objects :
      • ->sets
      • ->dictionary

Basic Structures¶

  • “null” type
  • booleans
  • numbers (integers, floating-point numbers, and complex numbers)

The None-Type¶

NoneType class that has exactly one object: None. None is used to represent the nothing. None appears frequently, and is often used as a placeholder in code. It is mainly use to check if an object is None.
Python reserves $is$ as an operation that checks if two objects are identical. This is different than ==, which checks if two objects are associated with the same value or state:

In [25]:
x = 22
y =None
print( x is None)
print( y is  None)
False
True

The Boolean Type¶

There are two boolean-type objects: True and False, the class name is bool. The results of comparison operation are generally bool.
True and False must be specified with capital letters in Python. These should not be confused with strings; note that there are no quotation marks used here.
$bool$ is a subclass of $int$ (see Numeric Types — int, float, complex). In many numeric contexts, False and True behave like the integers 0 and 1, respectively. However, relying on this is discouraged; explicitly convert using int() instead.

In [1]:
print(type(True))
print(isinstance(False, bool))
<class 'bool'>
True

Logic Operation¶

These are the Boolean operations, ordered by ascending priority:

Logic Operation Symbolic Operator
and &
or |

Comparisons¶

There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Operation Meaning
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
is object identity
is not negated object identity
In [2]:
# demonstrating boolean-logic operators
print(True or False)
print(True and False)
print(False)
True
False
False

Number¶

Integers¶

any “whole” number positive or negative, remember dynamic assignment. Their class is named int

In [4]:
print(type(245))

print(isinstance(1.3, int))

# converting a string to an integer
a=int("10")

# converting a floating-point number to an integer
int(1.3)

# from python 3 integer are not more conseserved with operation
print(2/3)
<class 'int'>
False
0.6666666666666666

Floating-Point Numbers¶

A “floating-point” number is a number with a decimal point. Their class is named float.
The is expressed in scientific notation 1e-5 and precision of depends on from the number of bit assigned to the float. Generally for most python float use 64-bit precision :

  • 1 sign bit
  • 11 bits exponent
  • 52 bits mantissa
In [20]:
print(type(-2.1))
print(type(3e-5))


# the integer 10 is not a float-type object
print(isinstance(10, float))


# including a decimal makes the number a float
print(isinstance(10., float))


# converting a string to a floating-point number
print(float("10.456"))

# converting an integer to a floating-point number
print(float(-22))

# but attention is numerical mathematic
print(0.1 + 0.1 + 0.1 == 0.3)

import math
print(math.isclose(0.1 + 0.1 + 0.1, 0.3))
<class 'float'>
<class 'float'>
False
True
10.456
-22.0
False
True

Complex Numbers¶

Is a number with the form $a+bi$, where a and b are real-valued numbers, and i is defined to be the number that satisfies the relationship $i^2=-1$. Because no real-valued number satisfies this relationship, is called the “imaginary number”. Weirdo electrical engineers use the symbol j in place of i, which is why Python displays the complex number as 2+3j.
Their class is named complex.

In [23]:
# Creating complex numbers
a= 2 + 3j
print( a)
a= complex(2,3)
print( a)

print( a+5)
print( a**2)
(2+3j)
(2+3j)
(7+3j)
(-5+12j)

Number operation¶

Opération Résultat
x + y somme de x et y
x - y différence de x et y
x * y produit de x et y
x / y quotient de x et y
x // y quotient entier de x et y
x % y reste de x / y
-x négatif de x
+x x inchangé
abs(x) valeur absolue de x
int(x) x converti en nombre entier
float(x) x converti en nombre à virgule flottante
complex(re, im) un nombre complexe avec re pour partie réelle et im pour partie imaginaire. im vaut zéro par défaut.
c.conjugate() conjugué du nombre complexe c
divmod(x, y) la paire (x // y, x % y)
pow(x, y) x à la puissance y

| x ** y | x à la puissance y

Logical operation Résultat
x | y bitwise or of x and y
x ^ y bitwise exclusive or of x and y
x & y bitwise and of x and y
x << n x shifted left by n bits
x >> n x shifted right by n bits
~x the bits of x inverted

Sequences data structure¶

A sequence is a positionally ordered collection of items. And you can refer to any item in the sequence by using its index number e.g., s[0] and s[1]. In Python, the sequence index starts at 0, not 1. So the first element is s[0] and the second element is s[1]. If the sequence s has n items, the last item is s[n-1].

  • Tuple
  • String
  • List

Python has the following built-in sequence types: lists, bytearrays, strings, tuples, range, and bytes.
Python classifies sequence types as mutable and immutable. The $mutable$ sequence types are lists and bytearrays while the $immutable$ sequence types are strings, tuples, range, and bytes.

A sequence can be $homogeneous$ or $heterogeneous$.
In heterogeneous sequences as list and tuple, you can store elements of different types including integer, strings, objects, etc.
In a homogeneous sequence as list, all elements have the same type. Strings are homogeneous sequences

Common Sequence Operations¶

The operations in the following table are supported by most sequence types, both mutable and immutable. This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s. The in and not in operations have the same priorities as the comparison operations. The + (concatenation) and * (repetition) operations have the same priority as the corresponding numeric operations.

Operation Result
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n or n * s equivalent to adding s to itself n times
s[i] ith item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.index(x[, i[, j]]) index of the first occurrence of x in s (at or after index i and before index j)
s.count(x) total number of occurrences of x in s

Tuple¶

A tuple is a sequence of arbitrary objects (a mix of numbers, strings, lists, other tuples, etc.). Tuples may be constructed in a number of ways:

  • Using a pair of parentheses to denote the empty tuple: ()
  • Using a trailing comma for a singleton tuple: a, or (a,)
  • Separating items with commas: a, b, c or (a, b, c)
  • Using the tuple() built-in: tuple() or tuple(iterable)
In [5]:
# creating a tuple
x = (1, "a", 2)  # tuple with 3 entries

# (3) does not make a tuple with one entry
# you must provide a trailing comma in this
# instance
y = 3, 4        # a tuple with 1 entry

#single element tuple
x1= (1,)
y1= 2,

print(type(x))
print(isinstance(y, tuple))
print(type(x1))
print(type(y1))


# the contents of a tuple cannot be changed: it is "immutable"
y = (1, "moo", None)  # (a, b, ...) creates a tuple
y[0] = 2
<class 'tuple'>
True
<class 'tuple'>
<class 'tuple'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[5], line 21
     19 # the contents of a tuple cannot be changed: it is "immutable"
     20 y = (1, "moo", None)  # (a, b, ...) creates a tuple
---> 21 y[0] = 2

TypeError: 'tuple' object does not support item assignment

Text Sequence Type — str¶

Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points. String literals are written in a variety of ways:

  • Single quotes: 'allows embedded "double" quotes'
  • Double quotes: "allows embedded 'single' quotes"
  • Triple quoted: '''Three single quotes''', """Three double quotes""" for multople line strings In a string, \n is treated as a single character. It denotes a new-line in a string, and will be rendered thusly when the string is printed. Similarly, \t will render as a tab-character.

Python’s strings have a large number of built-in functions available to them. It is very important that you familiarize yourself with these functions by looking over the official documentation. To demonstrate a few of these:

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
In [11]:
# few operation to familiarize
s = "S"
w = "Hello World"
print(type(w))
print(len(w))
print('w[6:11]  ',  w[6:11])
print('w[6:]    ',  w[6:])
print('w[:5]    ',  w[:5])

print('---\n')
str_a = "I love Python! "
str_b = "You too!"
print('str_a + str_b  ',str_a + str_b)
print(w.replace("World", "Berkeley"))
<class 'str'>
11
w[6:11]   World
w[6:]     World
w[:5]     Hello
---

str_a + str_b   I love Python! You too!
Hello Berkeley
In [6]:
# attention to don't mix different type #
x = 1
print("x = " + x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[6], line 3
      1 # attention to don't mix different type #
      2 x = 1
----> 3 print("x = " + x)

TypeError: can only concatenate str (not "int") to str

Formatting strings¶

Python provides multiple syntaxes for formatting strings; allowing to use the values of variables into strings, align fields using whitespace, and control the number of decimal places with which numbers are displayed in a string.

In Python 3, you can leverage the format method towards this end:

In [14]:
# using `format` to replace placeholders with values
"{name} is {age} years old".format(name="Bruce", age=80)  
Out[14]:
'Bruce is 80 years old'
In [15]:
#padding a string with leading-spaces so that it has at least 8 characters
"{item:>8}".format(item="stew")  
Out[15]:
'    stew'

For Python 3.6 or beyond, thenthere is the luxury of f-strings. allowing to add values directly in the string an example of an 'f-string'

In [16]:
batman = 12  
catwoman = 10  
f"Batman has {batman} apples. Catwoman has {catwoman} apples. Together, they have {batman + catwoman} apples"  
Out[16]:
'Batman has 12 apples. Catwoman has 10 apples. Together, they have 22 apples'

Formating table for int¶

'b' Binary format. Outputs the number in base 2.
'c' Character. Converts the integer to the corresponding unicode character before printing.
'd' Decimal Integer. Outputs the number in base 10.
'o' Octal format. Outputs the number in base 8.
'x' Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.
'X' Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. In case '#' is specified, the prefix '0x' will be upper-cased to '0X' as well.
'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.
None The same as 'd'.

Formating table for float¶

Type Meaning
'e' Scientific notation. For a given precision p, formats the number in scientific notation with the letter ‘e’ separating the coefficient from the exponent. The coefficient has one digit before and p digits after the decimal point, for a total of p + 1 significant digits. With no precision given, uses a precision of 6 digits after the decimal point for float, and shows all coefficient digits for Decimal. If no digits follow the decimal point, the decimal point is also removed unless the # option is used.
'E' Scientific notation. Same as 'e' except it uses an upper case ‘E’ as the separator character.
'f' Fixed-point notation. For a given precision p, formats the number as a decimal number with exactly p digits following the decimal point. With no precision given, uses a precision of 6 digits after the decimal point for float, and uses a precision large enough to show all coefficient digits for Decimal. If no digits follow the decimal point, the decimal point is also removed unless the # option is used.
'F' Fixed-point notation. Same as 'f', but converts nan to NAN and inf to INF.
'g' General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1. The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then, if m <= exp < p, where m is -4 for floats and -6 for Decimals, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used. With no precision given, uses a precision of 6 significant digits for float. For Decimal, the coefficient of the result is formed from the coefficient digits of the value; scientific notation is used for values smaller than 1e-6 in absolute value and values where the place value of the least significant digit is larger than 1, and fixed-point notation is used otherwise. Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.
'G' General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too.
'n' Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.
'%' Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.
None For float this is the same as 'g', except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully. For Decimal, this is the same as either 'g' or 'G' depending on the value of context.capitals for the current decimal context. The overall effect is to match the output of str() as altered by the other format modifiers.

Lists¶

Lists are mutable sequences, typically used to store collections of items. Lists may be constructed in several ways:

Using a pair of square brackets to denote the empty list: []
Using square brackets, separating items with commas: [a], [a, b, c]
Using a list comprehension: [x for x in iterable]
Using the type constructor: list() or list(iterable)
# a list-type object stores a sequence of other objects
>>> [3.5, None, 3.5, True, "hello"]
[3.5, None, 3.5, True, 'hello']

>>> type([1, 2, 3])
list

>>> isinstance([1, 2], list)
True

# constructing an empty list
>>> []
[]

# constructing a list with only one member
>>> ["hello"]
["hello"]

Lisinclude variables, equations, and other Python expressions in the list constructor; Python will simplify these expressions and construct the list with the resulting objects.

# the list constructor will simplify expressions
# and store their resulting objects
>>> x = "hello"
>>> [2 < 3, x.capitalize(), 5**2, [1, 2]]
[True, 'Hello', 25, [1, 2]]

Mutable Sequence Types Operations (list)¶

In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, bytearray only accepts integers that meet the value restriction 0 <= x <= 255).

*sort method is reserved to list

Operation Result
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
s.extend(t) or s += t extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop() or s.pop(i) retrieves the item at i and also removes it from s
s.remove(x) remove the first item from s where s[i] is equal to x
s.reverse() reverses the items of s in place
s.sort(key=None, reverse=False) sorts the list in place

Set Types — set, frozenset¶

A set object is an unordered collection of distinct $heterogenus$ objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
Like other collections, sets support x in set, len(set), and for x in set.
Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

There are currently two built-in set types, set and frozenset. The set type is mutable, frozenset type is immutable

The constructors for both classes work the same:

  • Use a comma-separated list of elements within braces: {'jack', 'sjoerd'}
  • Use a set comprehension: {c for c in 'abracadabra' if c not in 'abc'}
  • Use the type constructor: set(), set('foobar'), set(['a', 'b', 'foo'])

set,frozenset operations¶

Operation Equivalent Result
len(s) number of elements in set s (cardinality)
x in s test x for membership in s
x not in s test x for non-membership in s
s.issubset(t) s <= t test whether every element in s is in t
s.issuperset(t) s >= t test whether every element in t is in s
s.union(t) s | t new set with elements from both s and t
s.intersection(t) s & t new set with elements common to s and t
s.difference(t) s - t new set with elements in s but not in t
s.symmetric_difference(t) s ^ t new set with elements in either s or t but not both
s.copy() new set with a shallow copy of s

set operation¶

Operation Equivalent Result
s.update(t) s |= t return set s with elements added from t
s.intersection_update(t) s &= t return set s keeping only elements also found in t
s.difference_update(t) s -= t return set s after removing elements found in t
s.symmetric_difference_update(t) s ^= t return set s with elements from s or t but not both
s.add(x) add element x to set s
s.remove(x) remove x from set s; raises KeyError if not present
s.discard(x) removes x from set s if present
s.pop() remove and return an arbitrary element from s; raises KeyError if empty
s.clear() remove all elements from set s
In [19]:
set_1 = set([1, 2, 2, 3, 2, 1, 2])
set_1
Out[19]:
{1, 2, 3}
In [20]:
set_2 = set((2, 4, 6, 5, 2))
set_1.union(set_2)
Out[20]:
{1, 2, 3, 4, 5, 6}
# demonstrating set-comparison operations
>>> x = {"a", "b", "c", "d"}
>>> y = {"a", "b", "e"}

# union: items in x or y, or both
>>> x | y  # or x.union(y)
{'a', 'b', 'c', 'd', 'e'}

# intersection: items in both x and y
>>> x & y  # or x.intersection(y)
{'a', 'b'}

# difference: items in x but not in y
>>> x - y  # or x.difference(y)
{'c', 'd'}

# symmetric difference: in x or y, but not in both
>>> x ^ y  # or x.symmetric_difference
{'c', 'd', 'e'}

# check if set_1 is a superset of set_2
>>> {1, 2, 3, 4} >= {1, 2}
True

# check if set_1 and set_2 are equivalent sets
>>> {1, 2, 3, 4} == {1, 2}
False

Mapping Types — dict¶

A mapping object maps hashable values (immutable object) to arbitrary objects. There is currently only one standard mapping type, the dictionary (dict class). dict are mutable

Dictionaries can be created by several means:

  • Use a comma-separated list of key: value pairs within braces: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}
  • Use a dict comprehension: {}, {x: x ** 2 for x in range(10)}
  • Use the type constructor: dict(), dict([('foo', 100), ('bar', 200)]), dict(foo=100, bar=200)
In [21]:
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
f = dict({'one': 1, 'three': 3}, two=2)
a == b == c == d == e == f
Out[21]:
True

Let’s create the following grocery-to-price:

“cheese” ->2.53,
“milk”   ->3.40,
“frozen pizza” ->    8.01
# use a dictionary to map groceries to prices: item-name -> price
>>> items_to_prices = {"cheese": 2.53, "milk": 3.40, "frozen pizza": 8.01}

# looking up the price of "frozen pizza"
>>> items_to_prices["frozen pizza"]
8.01

Python’s dictionary is a shining star among its data structures; it is compact, fast, versatile, and extremely useful. It can be used to create a wide variety of mappings.

# keep track of whether or not a 3D coordinate fell into some region in space
# map (x, y, z) coordinates to "is in a region": (x, y, z) -> True/False
>>> point_to_region = {(0.1, 2.2, 3):False, (-10., 0, 4.5):True, (4.3, 1.0, 9.5):False}
>>> point_to_region[(-10., 0, 4.5)]
True

Dictionary methods¶

Method Description
Nonmutating methods
D.copy( ) Returns a shallow copy of the dictionary (a copy whose items are the same objects as D’s, not copies thereof)
D.has_key(k) Returns True if k is a key in D; otherwise, returns False, just like k in D
D.items( ) Returns a new list with all items (key/value pairs) in D
D.keys( ) Returns a new list with all keys in D
D.values( ) Returns a new list with all values in D
D.iteritems( ) Returns an iterator on all items (key/value pairs) in D
D.iterkeys( ) Returns an iterator on all keys in D
D.itervalues( ) Returns an iterator on all values in D
D.get(k[, x]) Returns D[k] if k is a key in D; otherwise, returns x (or None, if x is not given)
Mutating methods
D.clear( ) Removes all items from D, leaving D empty
D.update(D1) For each k in D1, sets D[k] equal to D1[k]
D.setdefault(k[, x]) Returns D[k] if k is a key in D; otherwise, sets D[k] equal to x and returns x
D.pop(k[, x]) Removes and returns D[k] if k is a key in D; otherwise, returns x (or raises an exception if x is not given)
D.popitem( ) Removes and returns an arbitrary item (key/value pair)
Mutating methods
D.clear( ) Removes all items from D, leaving D empty
D.update(D1) For each k in D1, sets D[k] equal to D1[k]
D.setdefault(k[, x]) Returns D[k] if k is a key in D; otherwise, sets D[k] equal to x and returns x
D.pop(k[, x]) Removes and returns D[k] if k is a key in D; otherwise, returns x (or raises an exception if x is not given)
D.popitem( ) Removes and returns an arbitrary item (key/value pair)
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: