Mike Mike - 1 year ago 109
Python Question

How to find a number that appears twice in a list and print it out in python?

I need some help with my homework for school. I am supposed to write a program in python that ask the person for a list of numbers, in my case:


and print out the numbers that appear twice in it in the same order they appeared. I am also supposed so use the
function in my program.

All I have currently is this:

list= eval(input("Input your list: "))

The end result is supposed to look like this in python shell:
Input a list: [53,16,22,81,43,16,88,55,43,5]

[16, 43]

Please help!

Answer Source

You could use list comprehension with count>1 as filter condition (and also index to make sure only the first of those occurrences is taken):

inp = eval(input('Input your list:'))
print([j for i, j in enumerate(inp) if inp.index(j) == i and inp.count(j) > 1])

Don't use list as a variable name, as it is an existing function in Python.

As stated by others: using eval is frowned upon, certainly when the argument is provided by the user.

Basic alternative (not efficient)

This just uses the most basic constructs:

result = []
n = len(inp)
for i in range(n):
    count = 0
    for j in range(n):
        if inp[i] == inp[j]:
            if j < i:
            count += 1
            if count > 1:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download