0% found this document useful (0 votes)
7 views

Topic 03 Data Types

Data types

Uploaded by

arthurlica29
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Topic 03 Data Types

Data types

Uploaded by

arthurlica29
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Topic3: Data Types / Structures in Python

Fundmental Data Type


Integer and Real Type
Literal Interpretation

1234, −24, 0, 99999999999999 Integers (unlimited size)

0o177, 0x9ff, 0b101010 Octal, hex, and binary literals in 3.X

1.23, 1., 3.14e-10, 4E210, 4.0e+210 Floating-point numbers

Arithmetic Operation (算術運算)

∘ Arithmetic Operators (算術運算符)


Operators Description

x+y Addition

x–y Subtraction

x*y Multiplication

x/y Division

x // y, x % y, divmod(x,y) quotient floor, Remainder

x ** y, pow(x,y) Power (exponentiation)

∘ Arithmetic Expression (算術表达式)


An arithmetic expression is an expression that results in a numeric value. It consists of arithmetic terms that are combined by arithmetic operations.

For example:

Expression in Math:

π π
ax2 + bx + c, 3sin + (5cos − 2)2
4 6
Expression in Python: ?

Characterisitcs of Variables in Expression


Variables are created when they are first assigned values.
Variables are replaced with their values when used in expressions.
Variables must be assigned before they can be used in expressions.
Variables refer to data objects stored in memory.

∘ Code Examples
Basic Calculation

In [1]: 20 + 30, 40 - 23.12, 12.3*(-2.5), 14.5/2, 15//6, 15%6, divmod(15, 6)

Out[1]: (50, 16.88, -30.75, 7.25, 2, 3, (2, 3))

In [2]: 3**4, 2**(1/2)

Out[2]: (81, 1.4142135623730951)

Using Variables

In [3]: a = 20
b = 0O24
c = 0x14
d = 0b10100
e = 20.0
a, b, c, d, e

Out[3]: (20, 20, 20, 20, 20.0)

In [4]: a = 123
b = bin(a)
o = oct(a)
h = hex(a)
a, b, o, h

Out[4]: (123, '0b1111011', '0o173', '0x7b')

In [5]: o1 = int(o, base=8)


o1

Out[5]: 123

In [6]: type(a), type(b), type(c), type(d), type(e)

Out[6]: (int, str, int, int, float)

In [7]: hex(a), oct(a), bin(a)

Out[7]: ('0x7b', '0o173', '0b1111011')

In [8]: a**2, e/(a+10)

Out[8]: (15129, 0.15037593984962405)

In [9]: a = 20
b = 20
c= 20
x = 1
a*x**2 + b*x + c

Out[9]: 60

In [10]: dir()

Out[10]: ['In',
'Out',
'_',
'_1',
'_2',
'_3',
'_4',
'_5',
'_6',
'_7',
'_8',
'_9',
'__',
'___',
'__builtin__',
'__builtins__',
'__doc__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'__vsc_ipynb_file__',
'_dh',
'_i',
'_i1',
'_i10',
'_i2',
'_i3',
'_i4',
'_i5',
'_i6',
'_i7',
'_i8',
'_i9',
'_ih',
'_ii',
'_iii',
'_oh',
'a',
'b',
'c',
'd',
'e',
'exit',
'get_ipython',
'h',
'o',
'o1',
'open',
'quit',
'x']

In [11]: from math import *


3*sin(pi/4) + 5*(cos(pi/6)-2)**2

Out[11]: 8.550812267870867

In [12]: from decimal import Decimal


Decimal('5.48') - Decimal('3.26')

Out[12]: Decimal('2.22')

In [13]: 5.48 - 3.26

Out[13]: 2.2200000000000006

In [14]: abs(1.1 + 2.2 - 3.3) < 1e-14

Out[14]: True

In [15]: print(f'{1.1:.16f} + {2.2:.16f} =? {3.3:.16f}')

1.1000000000000001 + 2.2000000000000002 =? 3.2999999999999998

In [16]: from math import *


exp((sin(pi/6)+cos(pi/3))**2) + 5*tan(pi/4 + pi/2)

Out[16]: -2.281718171540956

In [ ]:

In [17]: from decimal import Decimal


a = Decimal('1.1'); b = Decimal('2.2')
a + b

Out[17]: Decimal('3.3')

In [18]: exp(sin(pi/8)) + 7 * tan(pi/7)

Out[18]: 4.83723613240981

How to check what mathematical functions are available now?

How large number can python support?


In [20]: 2**(2000)

Out[20]: 11481306952742545242328332011776819840223177020886952004776427368257662613923703138566594863165062699184459646389874627734471189608630553314259313561666531853912998914531228000
06887791482400448714289269900634862447816154636463883639473170260404663539709049965581623988089446296056233116495361642219703326813441689089844585056023794848079140589009347765
00429002716706625830522008132236281291761267883317206598995396418127021779858404042159853183251540889433902091920554957783589672039160081957216630582755380425583726015528348786
419432054508915275783882625175435528800822842770817965453762184851149029376

In [21]: import sys


sys.float_info.min

Out[21]: 2.2250738585072014e-308

Bool Type

Logical Operation (邏輯運算)


∘ Expression of Logical Values
True(真) False(假)

∘ Relational Operators (關係運算符)


Relational Operators Description

x < y, x <= y Magnitude comparison

x > y, x >= y Magnitude comparison

x == y, x != y Value equality operators

x in y, x not in y Membership (iterables, sets)

x is y, x is not y Object identity tests

∘ Logical Operators (邏輯運算符)


Operators Description

x or y Logical OR (邏輯或)(y is evaluated only if x is false)

x and y Logical AND (邏輯與)(y is evaluated only if x is true)

not x Logical negation (邏輯⾮)

x if y else z Ternary selection (x is evaluated only if y is true)

∘ Logical Expression (邏輯表达式)


A logical expression is an expression that results in a logical value. It consists of logical terms that are combined by logical operations.

Expression in Logics:

¬(a ∧ b), ¬a ∧ b ∨ (c ∨ d)

Expression in Python:

not (a and b), (not a) and b or (c or d)

∘ Code Examples
Relational Expressions

In [22]: x = 3
y = 6
z = 8
x < y < z, x == y, x == 3, y != x, y >= x, x < y > z, 1.1 + 2.2 == 3.3, 1 + 2 == 3

Out[22]: (True, False, True, True, True, False, False, True)

Logical Expressions

In [23]: x = True
y = False
x and y, x or y, not x, 3 < 5 and 5 >= 8, x == 1, y == 0

Out[23]: (False, True, False, False, True, True)

In [24]: x = 100
y = 100

id(x), id(y), x is y

Out[24]: (4369971272, 4369971272, True)

String Type (字符串)

∘ Different ways to denote a string:


Single quotes: 'Tom"s', 'hello'
Double quotes: "Tom's", "hello"
Triple quotes: '''... spam ...''', """... spam ..."""
Escape sequences: "s\tp\na\0m"
Raw strings: r"C:\new\test.spm"
Bytes literals: b'sp\x01am'
Unicode literals : u'eggs\u0020spam'

In [25]: s0 = u'\u20AC'
print(s0)

∘ Escape Sequences Represent Special Characters:


Escape Meaning

\\ Backslash (stores one )

\' Single quote (stores ')

\" Double quote (stores ")

\a Bell

\b Backspace

\n Newline (linefeed)

\r Carriage return

\t Horizontal tab

\xhh Character with hex value hh (exactly 2 digits)

\ooo Character with octal value ooo (up to 3 digits)

\uhhhh Unicode character with 16-bit hex value (hhhh)

∘ Code Example
Define a string variable in different ways

In [26]: s1 = "The list company's age is: ten years"


s2 = 'The list company\'s age is: ten years'
s3 = """The list company's age is:

ten years"""
s4 = "The list company's age is: \nten years"
s5 = "The list company's age is:" + "\n" + "ten years"
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)

The list company's age is: ten years


The list company's age is: ten years
The list company's age is:

ten years
The list company's age is:
ten years
The list company's age is:
ten years

Output a string to a file/output device

Built-in print function

Print Objects
Format Strings
https://realpython.com/python-string-formatting/

In [ ]:

In [27]: s0 = "The IBM's revenue\" in 2020 is : $300B"


s1 = "The IBM's revenue\" in 2020 is : \n$300B"
s2 = '''The IBM's revenue\" in 2020 is :
$300B'''
print(s0)
print(s1)
print(s2)

Cell In[27], line 1


s0 = "The IBM's revenue\" in 2020 is : $300B
^
SyntaxError: EOL while scanning string literal

In [ ]: sr = r'C:\new\text.dat'
s = 'C:\new\text.dat'
print(sr, len(sr))
print(s, len(s))

C:\new\text.dat 15
C:
ew ext.dat 13

In [ ]: dir(str)

Out[ ]: ['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']

In [ ]: '周⽴刚'.encode().decode()

Out[ ]: '周⽴刚'

In [ ]: # bytes and unicodes in a string


codea = hex(ord('澳'))
codem = hex(ord('⻔'))
print(codea, codem)
s5 = '\u6fb3\u95e8'
print(s5)
print(chr(0x6fb3)) #ord('0'), chr(48) # character code converstions

0x6fb3 0x95e8
澳⻔

In [ ]: codes = '€'.encode()
print(codes)
sam = codes.decode()
print(sam)

b'\xe2\x82\xac'

In [ ]: code = b'\xE2\x82\xAC'
print(code.decode())

In [ ]: 1.1 + 1.1 == 2.2

Out[ ]: True

In [ ]: print(f'{1.1:.16f} + {2.2:.16f} = ? {3.3:.16f}')

1.1000000000000001 + 2.2000000000000002 = ? 3.2999999999999998

In [ ]: print('\u20AC'), print(b'\xE2\x82\xAC'.decode())



Out[ ]: (None, None)

The most widely-used UTF-8 codes

Fundamental Operations on String

∘ Basic Operations
In [ ]: s0 = 'hello,' ' world!'
s1 = 'hello,' + ' world!' # Concatenation: a new string
s2 = 'ab'*30 # Repetition: like '-'+'-'+...
print(s0)
print(s1)
print(s2)

hello, world!
hello, world!
abababababababababababababababababababababababababababababab

∘ Indexing and Slicing


No description has been provided for this image

In [ ]: s = 'HELLO, WORLD!'
len(s)

Out[ ]: 13

In [ ]: s[-6:]

Out[ ]: 'WORLD!'

In [ ]: s[0:5:2]

Out[ ]: 'HLO'

In [ ]: s = "HELLO, WORLD!"
print(s)
print(s[:])
print(s[::-1])
print(s[0] + "\t" + s[5] + "\t" + s[-1]) # indexing
print(s[0:5] + ' ' + s[0:-1:2] + ' ' + s[:-2])
# --------------Slice object----------------------------
so = slice(None, None, 2) #slice(start, end, step)
print(s[so]+'\n'+s[::2])

HELLO, WORLD!
HELLO, WORLD!
!DLROW ,OLLEH
H , !
HELLO HLO OL HELLO, WORL
HLO OL!
HLO OL!

∘ String converstion
In [ ]: '1' + 1

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-cc892b1f57d5> in <module>
----> 1 '1' + 1

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

In [ ]: type('1'), type(1)

Out[ ]: (str, int)

In [ ]: # float('1.1') + 1
str(1)
len(str(2**200))

Out[ ]: 61

In [ ]: float('1.1') + 2.2

Out[ ]: 3.3000000000000003

In [ ]: str(2)

Out[ ]: '2'

In [ ]: int('1') + 1

Out[ ]: 2

In [ ]:

In [ ]: num =input('Please input a number:')


print(f'The type of num is: {type(num)}')
print(int(num) + 10)

Please input a number:66


The type of num is: <class 'str'>
76

In [ ]: int('66'), str(66) # conversion between int and float

Out[ ]: (66, '66')

In [ ]: float('3.1415'), str(3.1415) # converstion between string and float

Out[ ]: (3.1415, '3.1415')

In [ ]: ord('0'), chr(48) # character code converstions

Out[ ]: (48, '0')

In [ ]: bin(10), oct(10), hex(10)

Out[ ]: ('0b1010', '0o12', '0xa')

∘ Changing Strings
In [ ]: s = "Macau is beautiful!, Macau is a small city!"
s

Out[ ]: 'Macau is beautiful!, Macau is a small city!'

In [ ]: s.replace('Macau', 'Zhuhai', 1)

Out[ ]: 'Zhuhai is beautiful!, Macau is a small city!'

In [ ]: help(s.replace)

Help on built-in function replace:

replace(old, new, count=-1, /) method of builtins.str instance


Return a copy with all occurrences of substring old replaced by new.

count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are
replaced.

In [ ]: dir(s)

Out[ ]: 78

In [ ]: s = 'Macau is beautiful!'
s = s.replace("Macau", "Zhuhai")
s

Out[ ]: 'Zhuhai is beautiful!'

In [ ]: s = 'this is a test string'


s = s.title()
s

Out[ ]: 'This Is A Test String'

▹ String Methods
Attribute fetches (对象属性访问)
An expression of the form object.attribute means “fetch the value of attribute in object.”

Call expressions (调⽤函数)


An expression of the form function(arguments) means “invoke the code of func tion, passing zero or more comma-separated argument objects to it, and return function’s result value.”

Methods (调⽤对象⽅法)
Putting above two together allows us to call a method of an object. The method call expression: object.method(arguments)

--- Align --- S.ljust(width [, fill]) S.center(width [, fill]) S.rjust(width [, fill]) S.zfill(width) --- Type --- S.isalnum() S.isalpha() S.isdecimal() S.isdigit() S.isidentifier() S.islower() S.isnumeric() S.isprintable() S.isspace() S.istitle() S.isupper() -- Changing -- S.capitalize() S.casefold()
S.title() S.upper() S.lower() S.swapcase() S.translate(map) S.maketrans(x[, y[, z]])S.lstrip([chars]) S.strip([chars]) S.rstrip([chars]) S.join(iterable) S.split([sep [,maxsplit]]) S.splitlines([keepends]) S.rsplit([sep[, maxsplit]]) S.rpartition(sep) --- Index, Find, Replace --- S.count(sub [,
start [, end]]) S.encode([encoding [,errors]]) S.partition(sep) S.endswith(suffix [, start [, end]]) S.replace(old, new [, count]) S.expandtabs([tabsize]) S.rfind(sub [,start [,end]]) S.find(sub [, start [, end]]) S.rindex(sub [, start [, end]]) S.format(fmtstr, *args, **kwargs) S.startswith(prefix
[, start [, end]]) S.index(sub [, start [, end]])

∘ List of Commonly Used String Methods in Python 3.x


All details about above functions

In [ ]: s = 'Macao'
s.center(30, '\u62ac')

Out[ ]: '抬抬抬抬抬抬抬抬抬抬抬抬Macao抬抬抬抬抬抬抬抬抬抬抬抬抬'

Complex Data Types − Data Collection

Why do we need data collection?


Expression in Mathematics:
Scalar(标量): x
Vector(向量): [x1 , x2 , … , xn ]
Matrix(矩阵):

⎡ 11 ⎤
x x12 ⋯ x 1n

⎢ ⋮ ⋮ ⋮ ⋮ ⎥⎥
⎣x xn2 ⋯ xmn ⎦
m1

Tensor(张量)3D:

Expression in Python:
Scalar ⇒ Simple Data Type: int, float, bool, string, ...
Vector, Matrix, Tensor 3D/ND ⇒ Complex Data Type (Data collection/container):
List
Dictionary
Tuple
Set, ...
String can be taken as a collection of characters.
Data collection is a container of different types of data.

List
Lists are Python's most flexible ordered collection object type.

Characteristics of List
Ordered collections of arbitrary objects
Accessed by offset/position
Variable-length, heterogeneous, and arbitrarily nestable
Mutable
Arrays of object references

List vs String
String ⟶ 字符串 List ⟶ 数据串

In [ ]: s = 'hello!'
ls = ['h', 'e', 'l', 'l', 'o', '!']
s2 = ''.join(ls)
print(s, s2)

ls2 = list(s)
print(ls, ls2)

hello! hello!
['h', 'e', 'l', 'l', 'o', '!'] ['h', 'e', 'l', 'l', 'o', '!']

In [ ]: # s[0] = 'I'
print(s[0])

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-d6f3b193531a> in <module>
----> 1 s[0] = 'H'

TypeError: 'str' object does not support item assignment

In [14]: ls[0] = 'H'


print(ls)

print(s.replace('h', 'H', 1))


print(s)

['H', 'e', 'l', 'l', 'o', '!']


Hello!
hello!

In [15]: help(s.replace)

Help on built-in function replace:

replace(old, new, count=-1, /) method of builtins.str instance


Return a copy with all occurrences of substring old replaced by new.

count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are
replaced.
List's Literals & Operations
Operations Interpretation -------------------------------------------------------------------- L = [] An empty list L = [123, 'abc', 1.23, {}] Four items: indexes 0..3 L = ['Bob', 40.0, ['dev', 'mgr']] Nested sublists L = list('spam') List of an iterable’s items L = list(range(-4, 4)) List of successive
integers -------------------------------------------------------------------- L[i] Index L[i][j] Index of index L[i:j] Slice len(L) Length -------------------------------------------------------------------- L1 + L2 Concatenate, repeat L * 3 -------------------------------------------------------------------- 3 in L
Membership -------------------------------------------------------------------- L.append(4) Methods: growing L.extend([5,6,7]) L.insert(i, X) --------------------------------------------------------------------- L.index(X) Methods: searching L.count(X) ---------------------------------------------------------
------------ L.sort() Methods: sorting, reversing, L.reverse() L.copy() Copying (3.3+) L.clear() Clearing (3.3+) --------------------------------------------------------------------- L.pop(i) Methods, statements: shrinking L.remove(X) del L[i] del L[i:j] L[i:j] = [] ---------------------------------------
------------------------------- L[i] = 3 Index assignment, slice assignment L[i:j] = [4,5,6] ---------------------------------------------------------------------- L = [x**2 for x in range(5)] List comprehensions and maps list(map(ord, 'spam')) --------------------------------------------------------------------
---
Introduction to List's Function

Lists in Action
In [3]: L0 = [1, 2, 3]
L1 = [4, 5, 6]
L2 = ['a', 1.25, L0]
# L0 + L1
L0 * 2

# L2,
# 3 in L0
# L0 + list('abc')

Out[3]: [1, 2, 3, 1, 2, 3]

In [4]: L2

Out[4]: ['a', 1.25, [1, 2, 3]]

In [2]: L2 = list(range(1,41))
print(L2)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]

In [12]: L2 = list(range(1,41))
del L2[:5]
print(L2)

[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]

In [11]: print(L2)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]

In [9]: L0 = [1, 2, 3]
L0.append('abc')
L0

Out[9]: [1, 2, 3, 'abc']

In [26]: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


matrix[0][2]

Out[26]: 3

In [20]: !pip install numpy

Requirement already satisfied: numpy in c:\users\lg\anaconda3\lib\site-packages (1.18.5)

In [27]: import numpy


a = numpy.random.rand(10)
rets = list(a)
# rets.sort(reverse=True)
# rets

Out[27]: [0.9876131375307133,
0.32637775354448384,
0.5452252886358093,
0.4404228570992531,
0.35873274133019406,
0.969737764650136,
0.18496098267691785,
0.16126736749201231,
0.2621545282338793,
0.8899567581363814]

In [19]: rets.sort()
rets.reverse()
rets

Out[19]: [0.9859582280497966,
0.9243012766252489,
0.8797263356487407,
0.752239932110347,
0.7003314363317287,
0.6499712105638575,
0.49908293235185375,
0.47642222220159036,
0.4762869565224409,
0.3776038279454894]

In [21]: help(rets.sort)

Help on built-in function sort:

sort(*, key=None, reverse=False) method of builtins.list instance


Sort the list in ascending order and return None.

The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
order of two equal elements is maintained).

If a key function is given, apply it once to each list item and sort them,
ascending or descending, according to their function values.

The reverse flag can be set to sort in descending order.

In [19]: # rets.sort(reverse=True)
rets

Out[19]: [0.9560069499728105,
0.9098878155961849,
0.7713933468131645,
0.6857339544590342,
0.6333260084398755,
0.5349982465408022,
0.49270975501254,
0.42325726732029456,
0.18090519650835946,
0.08122229081948418]

In [34]: L0 = 32
L1 = L0
L0 = 54
id(L0), id(L1)

Out[34]: (140720484400576, 140720484399872)

In [38]: # Methods call


L0 = ['Jack', 'Tom', 'Jane', 'Paul']
L1 = L0[:]
L0[1] = '2'
print(L0)
# L1 = L0
print(L1)
# L0.sort()
# id(L0), id(L1)
# L0, L1 # ??? very important

['Jack', '2', 'Jane', 'Paul']


['Jack', 'Tom', 'Jane', 'Paul']

In [37]: L0 = 'hello'
L1 = L0
L0 = 'world'
L1

Out[37]: 'hello'

In [14]: L1

Out[14]: ['Jack', 'Jane', 'Paul', 'Tom']

In [31]: L0 = ['Ja', 'tom', 'jane3', 'Paul']


L1 = L0
L0.sort()
L0, L1

Out[31]: (['Ja', 'Paul', 'jane3', 'tom'], ['Ja', 'tom', 'jane3', 'Paul'])

In [33]: L0.sort(key=len, reverse=True)


L0

Out[33]: ['jane3', 'Paul', 'tom', 'Ja']

In [22]: a = [1, 8, 2, 5, 7]
a.sort(reverse=True)
a
# a
# a.reverse()
# a

Out[22]: [8, 7, 5, 2, 1]

In [34]: L0.pop(2)
L0

Out[34]: ['jane3', 'Paul', 'Ja']

Dictionaries
Dictionaries are unordered collections whose items are stored and fetched by key , instead of by positional offset in list.

Characteristics of Dictionary
Accessed by key, not offset position
Unordered collections of arbitrary objects
Variable-length, heterogeneous, and arbitrarily nestable
Mutable
Tables of object references (hash tables)

Dictionary's Literals & Operations


Operations Interpretation ------------------------------------------------------------------------------------- D = {} Empty dictionary D = {'name': 'Bob', 'age': 40} Two-item dictionary E = {'cto': {'name': 'Bob', 'age': 40}} Nesting D = dict(name='Bob', age=40) Alternative construction
techniques: D = dict([('name', 'Bob'), ('age', 40)]) keywords, key/value pairs, zipped key/value D = dict(zip(keyslist, valueslist)) pairs, key lists D = dict.fromkeys(['name', 'age']) -------------------------------------------------------------------------------------- D['name'] Indexing by key
E['cto']['age'] 'age' in D Membership: key present test -------------------------------------------------------------------------------------- D.keys() Methods: all keys D.values() all values D.items() all key+value tuples D.copy() copy (top-level) D.clear() clear (remove all items) D.update(D2)
merge by keys D.get(key, default?) fetch by key, if absent default (or None) D.pop(key, default?) remove by key, if absent default (or error) D.setdefault(key, default?) fetch by key D.popitem() remove/return any (key, value) pair; etc. ------------------------------------------------------------
-------------------------- len(D) Length: number of stored entries D[key] = 42 Adding/changing keys del D[key] Deleting entries by key list(D.keys()) D1.keys() & D2.keys() --------------------------------------------------------------------------------------

Dictionaries in Action
In [1]: D = {'spam': 2, 'ham': 1, 'eggs': 3}
D2 ={'ham':4, 'toast':6}

D.keys(), D.values(), D.items(), len(D)

Out[1]: (dict_keys(['spam', 'ham', 'eggs']),


dict_values([2, 1, 3]),
dict_items([('spam', 2), ('ham', 1), ('eggs', 3)]),
3)

In [5]: 'ham' in D

Out[5]: True

In [41]: D['fish'] = 5
D

Out[41]: {'spam': 2, 'ham': 1, 'eggs': 3, 'fish': 5}

In [42]: D.update(D2)
D

Out[42]: {'spam': 2, 'ham': 4, 'eggs': 3, 'fish': 5, 'toast': 6}

In [43]: v = D.pop('toast')
D
# v

Out[43]: {'spam': 2, 'ham': 4, 'eggs': 3, 'fish': 5}

Usage Notes

Sequence operations don’t work. Dictionaries are mappings, not sequences.


Assigning to new indexes/keys adds entries.
Keys need not always be strings.

Tuples
Tuples work exactly like lists, except that tuples can't be changed in place, i.e. immutable.

Characteristics of Tuples
Ordered collections of arbitrary objects
Accessed by offset
Immutable
Fixed-length, heterogeneous, and arbitrarily nestable
Arrays of object references

Tuples' Literals & Operations


Operations Interpretation ---------------------------------------------------------------------------------- () An empty tuple T = (0,) A one-item tuple (not an expression) T = (0, 'Ni', 1.2, 3) A four-item tuple T = 0, 'Ni', 1.2, 3 Another four-item tuple (same as prior line) T = ('Bob', ('dev', 'mgr'))
Nested tuples T = tuple('spam') Tuple of items in an iterable ----------------------------------------------------------------------------------- T[i] Index, index of index, slice, length T[i][j] T[i:j] len(T) ----------------------------------------------------------------------------------- T1 + T2 Concatenate,
repeat T * 3 ----------------------------------------------------------------------------------- for x in T: print(x) Iteration, membership 'spam' in T [x ** 2 for x in T] ----------------------------------------------------------------------------------- T.index('Ni') Search, count T.count('Ni') namedtuple('Emp',
['name', 'jobs']) Named tuple extension type ------------------------------------------------------------------------------------

In [28]: dir(())

Out[28]: ['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'count',
'index']

Tuples in Action
In [29]: t0 = (30)
t1 = (30,)
type(t0), type(t1)
# t0, t1 # t0 is an integer, t1 is a tuple, !!the output of this line is a nested tuple

Out[29]: (int, tuple)

In [46]: T = (1, 3, 2, 4, 2, 5, 2)
T.index(2), T.index(2,3), T.count(2), T.index(2, T.count(2))

Out[46]: (2, 4, 3, 4)

In [30]: help(().index)

Help on built-in function index:

index(value, start=0, stop=9223372036854775807, /) method of builtins.tuple instance


Return first index of value.

Raises ValueError if the value is not present.

In [49]: T = list(T)
T[1] = 8
T = tuple(T)
T

Out[49]: (1, 8, 2, 4, 2, 5, 2)

Why do we need Tuples when we have Lists?


Ans:

The immutability of tuples provides some integrity—you can be sure a tuple won’t be changed through another reference elsewhere in a program, but there’s no such guarantee for lists. Tuples and other
immutables, therefore, serve a similar role to “constant” declarations in other languages.

Set
An unordered collection of unique and immutable objects that supports operations corresponding to mathematical set theory.

Characteristics of Set
Items are stored only once in a set, i.e. no duplication
Items can not be revised directly
Set can be revised by internal methods

In [19]: so = {1, 3, 5, 7}
se = {2, 4, 6, 8}
s = set(range(5))
print(f's={s}')
soe = so | se # OR
s0 = s & so # AND
s1 = s - so # Difference
s2 = s ^ so # XOR
so > se, so < se

print(soe)
print(s0)
print(s1)
# dir(so)
# help(s0.difference_update)
# so.difference_update(s)
help(so.add)

s={0, 1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 3}
{0, 2, 4}
Help on built-in function add:

add(...) method of builtins.set instance


Add an element to a set.

This has no effect if the element is already present.

In [56]: s = {1, 4, 7}
s.add('abc')
s

Out[56]: {1, 4, 7, 'abc'}

You might also like