Data Structure and Sequences
Tuple
A tuple is a fixed-length, immutable sequence of Python objects.
The easiest way to create one is with a comma seperated sequence of values
tup = 1, 2, 3, 4
List
Lists are variable-length and their contents can be modified in-place.
They can be defined using square brackets [] or using the
list
type function.
a_list = [2, 3, 7, None]
tup = ('foo', 'bar', 'bin')
b_list = list(tup)
Adding and Removing elements
Elements can be appended to the end of the list
b_list.append('dwarf')
b_list
['foo', 'bar', 'bin', 'dwarf']
An element can be removed from the list with pop
or remove
b_list.pop(2)
'bin'
b_list
['foo', 'bar', 'dwarf']
b_list.remove('bar')
b_list
['foo', 'dwarf']
Concatenating and extending lists
x = [4, None, 'foo']
y = x + [7, 8, 9]
y
[4, None, 'foo', 7, 8, 9]
y.extend([12, 13, 14])
y
[4, None, 'foo', 7, 8, 9, 12, 13, 14]
Dict
The dict is similar to a hash map or associative array in other languages.
It is a collection of key-value pairs where the key and value are Python objects.
It is usually created using curly braces {}.
d1 = {'a':'apple', 'b':[1, 2, 3, 4]}
d1
{'a':'apple', 'b':[1, 2, 3, 4]}
d1[7] = 'James Bond'
d1
{'a':'apple', 'b':[1, 2, 3, 4], '7':'James Bond'}
d1['b']
{[1, 2, 3, 4]}
'b' in d1
True
Set
A set is an unordered collection of unique elements, like dict without values.
A set can be created with the set function or curly braces {}
set([2, 2, 2, 1, 3, 3])
{1, 2, 3}
{2, 2, 2, 1, 3, 3}
{1, 2, 3}
a = {1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7, 8}
a.union(b)
{1, 2, 3, 4, 5, 6, 7, 8}
a.intersection(b)
{3, 4, 5}
Set operations include add(x)
, clear
, remove
, pop
, union
, update
, intersection(b)
, intersection_update(b)
, difference(b)``, difference_update(b)
, symmetric_difference(b)
symmetric_difference_update(b)
, issubset(b)
, issuperset(b)
, isdisjoint(b)
.