Hey guys so this is my first year programming and I started with python. I am understanding the programming fairly well but I need help with this homework question.
I have to use a list as my parameter and then return the number of different values in the list. The example list in the question is [1, 4, 1, 7, 6, 1, 4, 3] and therefore the returned value should be 5.
Now I know my method of solving it is probably not concise or elegant but if someone could help me and tell me what to change so it works I would greatly appreciate it.
def count(mylist):
newlist = []
newlist.append(mylist[0])
stor = False
for i in mylist:
stor = False
for j in newlist:
if j == i:
stor == True
if not stor:
newlist.append(i)
return newlist
At first, a fixed version of your program
And here some suggestions:
storoutside the outer loop. This is done two lines later again.breakin the inner loop – this speeds things up a bit (no unneeded comparison)newlistcan be initialized to an empty list without appending the first item. The algorithm stays valid (the inner loop have zero iterations the first time)here as code-example:
And more elegant (and pythonic): use the
in-syntax 😉Basically
item in something_iterablereturns true, ifitemcan be found insomething_iterable. Most collection of items is iterable (e.g. lists, sets, strings …'a' in 'abc'returns true )and the most pythonic way but without for/while-loops:
Please look into other answers for an explanation.