Code:
new_list2 = [["hey" if x %2 == 0 else x for x in row] for row in theList]
Security Code:
theList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] newList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for i in range(len(theList)): for j in range(len(theList)): if theList[i][j] % 2 == 0: newList[i][j] = "hey'ere" new_list2 = [["hey'ere" if x %2 == 0 else x for x in row] for row in theList] assert newList == new_list2
Or...
Or, if you literally replace the elements in newList based on the values in theList , you can do:
newList = [[10, 20, 30], [40, 50, 60], [70, 80, 90]] newList[:] = [["hey" if x % 2 == 0 else y for x, y in zip(row1, row2)] for row1, row2 in zip(theList, newList)] print(newList)
Results:
[[10, 'hey', 30], ['hey', 50, 'hey'], [70, 'hey', 90]]