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()
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)))
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))
In [4]:
for element in [1, 's', [1, 3], 1j]:
print(element, end=' ')
In [5]:
for letter in "hello world":
print(letter, end=' ')
In [6]:
mydict = {'key1': 1, 'key2': 2}
for key in mydict:
print("%s: %s" % (key, mydict[key]))
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))