I have a piece of code that loops until an error is raised or a value of None is assigned to the variable "parent." On each loop, it appends a value to a list, known as actionList. Through print statements, I know that the list is growing through each iteration of the loop. However, after I exit the loop (through a KeyError that is caught), print statements reveal that the list is now assigned a value of None. Any idea what's going on?
while parent is not None:
print "iterating"
print actionList
try:
pathList.append(parentMap[parent])
except KeyError:
break
actionList.append(actionMap[parent])
parent = parentMap.get(parent, None)
return actionList.reverse()
Upon further examination, it looks like the actionList is still intact once I leave the loop. However, when the reverse() method is used on actionList, it disappears. Am I using reverse() wrong?
Yes. reverse
reverses the list in place and returns None. Do this instead:
actionList.reverse()
return actionList
You could also do return list(reversed(actionList))
, which will return a reversed copy of the list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.