Peter Huba Peter Huba - 24 days ago 8
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:
new_list.append(a)
return new_list


Working code (not from me):

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

Answer

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:
                new_list.append(a)

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