One of the answers in "python way" to parse and conditionally replace every element in 2D list has revealed to me that I understand even less than I thought.
Given a list of lists containing strings:
myLists = [['5','cat','23'],
['33','parakeet','scalpel'],
['correct','horse','battery','staple','99']]
I wish to replace each element with the return of:
def numParser(string):
try:
return int(string)
except ValueError:
return string
My original code was this, but it does not modify the original array. I assumed because list
is a copy, not the actual list (am I wrong?):
for single_list in myLists:
single_list = map(numParser, rawData)
And one of the answers which modifies the lists in place is:
for single_list in myLists:
for i, item in enumerate(single_list):
single_list[i] = numParser(item)
Why does the second solution work but not the first?