[ Iterating through the list index by index ]
iterating through the list index by index
b = [2, 4, 5, 6]
for index, item in enumerate(b):
print(index, item)
if not item % 2:
b.remove(item)
print(b)
Dynamic binding and typos in variable names
print('first list:')
for i in range(3):
print(i)
print('\nsecond list:')
for j in range(3):
print(i) # I (intentionally) made typo here!
List slicing using indexes that are "out of range"
my_list = [1, 2, 3, 4, 5]
print(my_list[5])
Reusing global variable names and UnboundLocalErrors
def my_func():
print(var)
var = 'global'
my_func()
No problem to use the same variable name in the local scope without affecting the local counterpart:
def my_func():
var = 'locally changed'
var = 'global'
my_func()
print(var)
we have to be careful if we use a variable name that occurs in the global scope, and we want to access it in the local function scope if we want to reuse this name:
def my_func():
print(var) # want to access global variable
var = 'locally changed' # but Python thinks we forgot to define the local variable!
var = 'global'
my_func()
We have to use the global keyword!
def my_func():
global var
print(var) # want to access global variable
var = 'locally changed' # changes the gobal variable
var = 'global'
my_func()
print(var)
Creating copies of mutable objects
my_list1 = [[1, 2, 3]] * 2
print('initially ---> ', my_list1)
modify the 1st element of the 2nd sublist
my_list1[1][0] = 'a'
print("after my_list1[1][0] = 'a' ---> ", my_list1)
we should better create "new" objects:
my_list2 = [[1, 2, 3] for i in range(2)]
print('initially: ---> ', my_list2)
modify the 1st element of the 2nd sublist
my_list2[1][0] = 'a'
print("after my_list2[1][0] = 'a': ---> ", my_list2)
for a, b in zip(my_list1, my_list2):
print('id my_list1: {}, id my_list2: {}'.format(id(a), id(b)))
Abortive statements in finally blocks
def try_finally1():
try:
print('in try:')
print('do some stuff')
float('abc')
except ValueError:
print('an error occurred')
else:
print('no error occurred')
finally:
print('always execute finally')
try_finally1()