py_tip_03.py

#!/usr/bin/python3
# ==================================================================
# use enumerate to display ...
# ------------------------------------------------------------------
# The major difference between tuples and lists is that a list is
# mutable and a tuple is immutable. This means that a list can be
# changed, but a tuple cannot.
# ------------------------------------------------------------------
# Tuples are used to store heterogeneous elements, which are
# elements belonging to different data types. Lists, on the other
# hand, are used to store homogenous elements, which are elements
# that belong to the same type.
#
# Note that this is only a semantic difference. You can store
# elements of the same type in a tuple and elements of different
# types in a list.
# ==================================================================

class Person():
    pass

print('-------------------------------------')

# ----- create a list
lx = [ 1, 2, Person(), 'abc', 'xyz']

print('lx is a ',type(lx))

# ----- create a tuple
tx = (1, 2, Person(), 'abc', 'xyz')

print('tx is a ',type(tx))

# ----- create a dictionary
dx = { 'A': 1,     'B': 2, 'C': Person(),
       'D': 'abc', 'E': 'xyz'}

print('dx is a ', type(dx))

print('----LIST---------------------------------')

# use enumerate to display list elements
for idx,x in enumerate(lx):
    print('lx ',idx,'  value=',x,' type=', type(x))

print('----TUPLE--------------------------------')

# use enumerate to display a tuple
for idx,x, in enumerate(tx):
    print('tx ',idx,'  value=',x,' type=', type(x))

print('----DICTIONARY---------------------------')

# use enumerate to display a dictionary values
# NOTE: idx is the enumeration index and not
# the dictionary key index

for idx,k in enumerate(dx):
    print('dx ',idx,'  key=',k,' type=', type(k))
    v = dx[k]
    print('dx ',idx,'  value=',v,'  type=', type(v))

print('----INDIVIDUAL ELEMENTS-----------------')

# access individual elements
idx = 4

print('lx[',idx,'] =',lx[idx])

idx = 2
print('tx[',idx,'] =', tx[idx])

idx = 'A'
print('dx[',idx,'] =', dx[idx])
idx = 3
print('dx.keys()=', dx.keys())
print('list(dx)[',idx,']=', list(dx)[idx])
print('dx[list(dx)[',idx,']])=',dx[list(dx)[idx]])