Reputation: 395
Write a function which takes a list of strings as input and returns unique values in the list.
Sample:
>>> unique_list(['cat', 'dog', 'cat', 'bug', 'dog', 'ant', 'dog', 'bug'])
['cat', 'dog', 'bug', 'ant']
My current code:
def unique_list(input_list):
for word in input_list:
if word not in input_list:
output_list = [word]
return output_list
print(output_list)
I get this error(s):
> Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
unique_list(['cat', 'dog', 'cat', 'bug', 'dog', 'ant', 'dog', 'bug'])
File "/Users/****/Desktop/University/CompSci 101/Lab Work/Lab 05/lab05_Homework.py", line 12, in unique_list
print(output_list)
UnboundLocalError: local variable 'output_list' referenced before assignment
What am I doing wrong?
Upvotes: 0
Views: 7564
Reputation: 501
Here are minor, but critical, changes to your code:
def unique_list(input_list):
output_list = []
for word in input_list:
if word not in output_list:
output_list.append(word)
print(output_list)
return output_list
Upvotes: 1
Reputation: 32189
Your if
statement is never True
.
That is because you are getting word
from the list and then checking that it is not in it. Doesn't make sense since the only way you got word
from input_list
is if it was in it. Therefore, your output_list
never gets created and so when you try to print it, you get the error that the local variable 'output_list'
referenced before assignment.
However, I suggest an easier way to get unique elements would be to use sets:
>>> print list(set(['cat', 'dog', 'cat', 'bug', 'dog', 'ant', 'dog', 'bug']))
['cat', 'dog', 'bug', 'ant']
Sets are "Unordered collections of unique elements" and therefore when you cast a list of repeating elements as a set, it will get the unique elements which you can then cast back to a list as I did above with list(your_set)
to print it.
Alternatively, if this is some kind of coding practice and you want to stick to your method, just add an initialization line for output_list
in your method as follows:
def unique_list(input_list):
output_list = []
... #Rest of your code
>>> nums = [0,1,2,3,4]
>>> for i in nums:
... if i not in nums:
... print 'True'
... else:
... print 'False'
False
False
False
False
False
Upvotes: 5