I have this 2d list. I want to derive the cam models with most units sold, and the array has 2 models tied for that. I've defined a function to return the quantity and index of the brands. The quantity and index are getting appended to a new list, but when I try to concatenate the values from the original 2d list, the concatenation is not successful and it is only showing the name of the first model. Can someone explain what's going wrong here?
UnitSold = [['Dash Cam Model', 'SJ Branch', 'PJ Branch', 'KL Branch'], ['RS Pro with GPS', 5, 4, 3],
['Transcend Drive Pro', 2, 2, 3], ['H203 1080P', 3, 2, 5], ['Pioneer', 4, 5, 3]]
def maxItem():
n = 0
k: list = []
for i in range(1, len(UnitSold)):
m = 0
for j in range(1, len(UnitSold[i])):
m += UnitSold[i][j]
if m >= n:
n = m
k.append(n)
k.append(i)
return k
return k
This method works and the list has 4 values appended to it when you print this function.
Whereas this method only prints 2 values, the total quantity and the model name which loads earlier.
def maxItem():
n = 0
k: list = []
str = ""
for i in range(1, len(UnitSold)):
m = 0
for j in range(1, len(UnitSold[i])):
m += UnitSold[i][j]
if m >= n:
n = m
str += UnitSold[i][0]
return str, n
return str, n
I'm posting this as an answer because it makes it easier to explain.
Here is your first example with my comments on what is happening.
Here is your second example which essentially does the same thing in a slightly different way. The only difference is you hand back a Tuple rather than a list, and you hand back the value of the first element rather than the first element.
As a side note, you shouldn't name a variable
str
as that is already used as a builtin type (meaning string).It would also be helpful in seeing how you are calling this function.