Containers

Create containers with literals


In [1]:
aString = "123456"
aList = [1, 2.0, 1j, 'hello', [], {}, (1, 2)]
aSet = {1, 2.0, 1j, 'hello', (1, 2)}
aTuple = (1, 2.0, 1j, 'hello', [], {}, (1, 2))
aDict = {
    1: 1,
    2.0: 2.0,
    1j: 1j,
    (1, 2): (1, 2),
    'hello': 'hello',
    'list': [],
    'dict': {},
}

iterables = [
    aString,
    aList,
    aSet,
    aTuple,
    aDict,
]

for iterable in iterables:
    print('iterating over %s' % (type(iterable)))
    for element in iterable:
        print(element, end=' ')
        if isinstance(iterable, dict):
            print('(value: %s)' % (str(iterable[element])), end=' ')
    print()


iterating over <class 'str'>
1 2 3 4 5 6 
iterating over <class 'list'>
1 2.0 1j hello [] {} (1, 2) 
iterating over <class 'set'>
(1, 2) 1 2.0 1j hello 
iterating over <class 'tuple'>
1 2.0 1j hello [] {} (1, 2) 
iterating over <class 'dict'>
(1, 2) (value: (1, 2)) 1 (value: 1) 2.0 (value: 2.0) 1j (value: 1j) hello (value: hello) dict (value: {}) list (value: []) 

Create containers with constructor functions


In [2]:
aList = list((1, 2.0, 'hello', []))
aSet = set(([1, 2.0, 'hello']))
aTuple = tuple([1, 2.0, 'hello', []])
aString = str(['a', 'b', 'c'])
aDict = dict(key1='value', key2=1j, key3=[1, 2, {}])
iterables = [
    aList,
    aSet,
    aString,
    aDict,
]

for iterable in iterables:
    print(iterable, (type(iterable)))


[1, 2.0, 'hello', []] <class 'list'>
{1, 2.0, 'hello'} <class 'set'>
['a', 'b', 'c'] <class 'str'>
{'key2': 1j, 'key1': 'value', 'key3': [1, 2, {}]} <class 'dict'>

Explore more containers


In [3]:
import collections


def func():
    pass


class Cnt(object):
    """Container but not iterable"""
    def __contains__(self, _):
        return True


for obj in [1, 1.0, 1j, 's', None, True, [], (1, 2), {}, {1}, object, collections, func, Cnt, Cnt()]:
    isContainer = isinstance(obj, collections.Container)
    isIterable = isinstance(obj, collections.Iterable)
    isHashable = isinstance(obj, collections.Hashable)
    print ("%s %s; container: %s; sequence: %s; hashable: %s" %
           (obj, type(obj), isContainer, isIterable, isHashable))


1 <class 'int'>; container: False; sequence: False; hashable: True
1.0 <class 'float'>; container: False; sequence: False; hashable: True
1j <class 'complex'>; container: False; sequence: False; hashable: True
s <class 'str'>; container: True; sequence: True; hashable: True
None <class 'NoneType'>; container: False; sequence: False; hashable: True
True <class 'bool'>; container: False; sequence: False; hashable: True
[] <class 'list'>; container: True; sequence: True; hashable: False
(1, 2) <class 'tuple'>; container: True; sequence: True; hashable: True
{} <class 'dict'>; container: True; sequence: True; hashable: False
{1} <class 'set'>; container: True; sequence: True; hashable: False
<class 'object'> <class 'type'>; container: False; sequence: False; hashable: True
<module 'collections' from '/home/obestwalter/.pyenv/versions/3.4.4/lib/python3.4/collections/__init__.py'> <class 'module'>; container: False; sequence: False; hashable: True
<function func at 0x7f86dc4c47b8> <class 'function'>; container: False; sequence: False; hashable: True
<class '__main__.Cnt'> <class 'type'>; container: False; sequence: False; hashable: True
<__main__.Cnt object at 0x7f86dc4c5860> <class '__main__.Cnt'>; container: True; sequence: False; hashable: True

Iterables


In [4]:
for element in [1, 's', [1, 3], 1j]:
    print(element, end=' ')


1 s [1, 3] 1j 

In [5]:
for letter in "hello world":
    print(letter, end=' ')


h e l l o   w o r l d 

In [6]:
mydict = {'key1': 1, 'key2': 2}
for key in mydict:
    print("%s: %s" % (key, mydict[key]))


key2: 2
key1: 1

NOTE: dict.items() returns a tuple with key and value of the current dictionary element whith each iteration which is then unpacked directly into the two names key and value.


In [7]:
for key, value in {'k1': 1, 'k2': 2}.items():
    print("%s: %s" % (key, value))


k1: 1
k2: 2