Python Data Structures
Single-value data structures (all immutable): int float bool (We often treat string information—textual data—as a single value, though it’s technically multiple-value as shown below.)
Type Constant values Selected operators Selected functions Uses
int 0 -17 238653489 + - * / % // ** == != > < >= <= abs() max() min() Counting things; indexing strings or lists
float 3.0 -2.00053 3.5e19 + - * / % // ** == != > < >= <= abs() max() min() Calculating real-world quantities
`
bool True False and or not == != Results of comparisons, yes-or-no questions
Multiple-value data structures: string list namedtuple file dict set tuple
Type Mutable Sequence Constant values Selected operators and Selected methods Main Uses
(can change (are items functions characteristics
in place)? in order)?
string No Yes '' 'Four score and 7 ...' in + * [ ] [ : ] S.find() Indexable sequence Text, names, words, “ASCII
"We the people ..." len() S.split() S.strip() of characters, can graphics” like
''' Multi-line string can == != > < >= <= S.format() take “slices” ************
span many lines ''' int() float() S.translate() (substrings)
list (also Yes Yes [ ] [1, 2, 3] ['Hello!'] in + * [ ] [ : ] L.count() L.sort() Indexable sequence, General collection of same-
called array) len() min() max() L.append() can take “slices” type objects
== != > < >= <= L.extend()
namedtuple No Yes Restaurant('Taillevent', . [to specify field/attribute] R = R._replace Access to from collections
(also called 'French', '333-4444', print(R.name, 'has', (name='Noma') components by import namedtuple
structure or 'Gateau Marjolaine', R.dish, 'for $', attribute/field name Grouping components of
record) 33.00) R.price) an object (e.g., student
name, ID, major, GPA)
file No Yes inf = open('blah.txt', nextline = Files give you Saving data from one run
'r') inf.readline() persistence: Their to the next; preparing input
outf = open('ans.txt', linelist = contents stay around to another program;
'w') inf.readlines() after the program packaging data to send over
outf.writelines() stops running. the net
outf.close()
dict (also Yes No { } in [ ] d.items() #view No order; look up Programmer-defined
map, table, {'Joe':25, 'Jan': 47, len() d.keys() #view value by key indexes, fast lookup
dictionary) 'Jill':44, 'Jim': 45} == != > < >= <= d.values() #view
set Yes No set() {'a', 'b', 'c'} in len() >= <= | & S.add() No order, no Eliminate duplicates
S.remove() duplicates
tuple No Yes ( ) in [ ] T.count() Grouped data, Short multi-part data
('Joe', 'Smith', 19, len() access by position packages where field names
'Informatics') == != > < >= <= not needed
('Donald',) # One item
[Compiled by David G. Kay. Errors or suggestions to [email protected]. Copyright © 2013 by David G. Kay. Permission to copy for individual nonprofit academic purposes only.]