Peter Huba Peter Huba - 1 year ago 103
Python Question

Code not performing as expected [For in cycle]

Why is this not working? Actual result is

for any entry.

def non_unique(ints):
Return a list consisting of only the non-unique elements from the list lst.

You are given a non-empty list of integers (ints). You should return a
list consisting of only the non-unique elements in this list. To do so
you will need to remove all unique elements (elements which are
contained in a given list only once). When solving this task, do not
change the order of the list.

>>> non_unique([1, 2, 3, 1, 3])
[1, 3, 1, 3]
>>> non_unique([1, 2, 3, 4, 5])
>>> non_unique([5, 5, 5, 5, 5])
[5, 5, 5, 5, 5]
>>> non_unique([10, 9, 10, 10, 9, 8])
[10, 9, 10, 10, 9]

new_list = []
for x in ints:
for a in ints:
if ints.index(x) != ints.index(a):
if x == a:
return new_list

Working code (not from me):

result = []
for c in ints:
if ints.count(c) > 1:
return result

Answer Source

list.index will return the first index that contains the input parameter, so if x==a is true, then ints.index(x) will always equal ints.index(a). If you want to keep your same code structure, I'd recommend keeping track of the indicies within the loop using enumerate as in:

for x_ind, x in enumerate(ints):
    for a_ind, a in enumerate(ints):
        if x_ind != a_ind:
            if x == a:

Although, for what it's worth, I think your example of working code is a better way of accomplishing the same task.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download