Home > database >  Python: Converting user input to list then getting common elements
Python: Converting user input to list then getting common elements

Time:08-07

How would I convert a user input into a list and the find common elements within both lists? Currently I'm doing this:

lst = []
lst2 = []
while True:
    seq1 = input('first list: ')
    break
while True:
    seq2 = input('second list: ')
    break

print(list(set(lst).intersection(lst2)))

My output returns a empty list.

CodePudding user response:

It's a doddle with the sets, isn't it?

I think the problem here is that your lists are empty because you're not reading any data into them (you're just reading data into seq1 and seq2).

The way I'd do it (without loops and all) is:

Read data into strings seq1 and seq2 in a particular format.

seq1 = input('first list: ')
seq2 = input('second list: ')

Split the data into a list. I split along spaces in the snippets, but you can provide any character as an argument (so you can alos have comma-separated elements if you want).

lst1 = seq1.split() # I renamed lst to be consistent
lst2 = seq2.split() # default: split along ' ' (space)

Construct sets from the list.

set1 = set(lst1)
set2 = set(lst2)

Take the intersection.

print(set1.intersection(set2))

CodePudding user response:

You probably want to split the inputs in order to convert them from single strings to lists of strings, which you can then convert into sets in order to take the intersection.

>>> print(set(input('first list: ').split()) & set(input('second list: ').split()))
first list: foo bar baz
second list: bar ola baz qux
{'bar', 'baz'}

CodePudding user response:

I am not that good with that sort of stuff but you could make a for loop which looks something like this:

for i in seq1:
    lst.append(seq1[i])

You can do that for both with another for loop.

But if you only want to compare them, you don't have to turn the strings into lists, you could just refer to them as you would elements in lists, as I did with the code above when I said 'seq1[i]'.

The better way to make the strings into a list (thanks to @mpp) is to just to set the input to a list as such:

seq1 = list(input('first list: '))

CodePudding user response:

i would recommend using sets instead of lists because you can store unique elements with them and the intersection function works well with it.

here is how i would do it in 3 lines:


input1 = set(input("first set: "))
input2 = set(input("second set: "))

print(input1.intersection(input2))

the while loops you have doesn't help with anything, try to eliminate the loops when you don't need them

  • Related