Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store many inputs from a user in a set [duplicate]

My aim is to have many inputs from a user stored in a disordered manner. So, I decided to use a set. The code I have so far is:

a = input()
b = input()
c = input()
d = input()

all = a, b, c, d
print(set(all))

However, I do not want to repeat input() several times like above. Is there a way to achieve this?

like image 431
Ololade Avatar asked Nov 29 '22 21:11

Ololade


1 Answers

If all you want is a set you do not need a, b, c, d.

all = set()   #or all = {*(),}
for _ in range(4):
    all.add(input())

print(all)

Or,

all = {input() for _ in range(4)}

This is considering you take the inputs in new line. Otherwise, if the input are comma-separated for example:

all = set(input().split(','))
print(all)

or

all = {*input().split(',')}
print(all)

In case you need both a, b, c, d and all the inputs, you could do:

>>> all = a, b, c, d = {*input().split(',')}
# example
>>> all = a, b, c, d = {1, 2, 3, 4}
>>> all
{1, 2, 3, 4}
>>> a
1
>>> b
2

As pointed out by @Tomerikoo all(iterable) is a built-in function avoid naming your variables same as python builints or keywords. Another point, if in case you have already done so, in order to get the default behavior of all, you could do:

>>> import builtins
>>> all = builtins.all
# Or, more conveniently, as pointed out by @Martijn Pieters
>>> del all
  • * is used for iterable unpacking
  • _ is used for don't care or throwaway or anonymous variable, as we do not need the variable in the loop. More on this here.
  • {*()} is just a fancy way of creating empty sets as python does not have empty set literals. It is recommended to use set()
like image 189
Sayandip Dutta Avatar answered Dec 06 '22 09:12

Sayandip Dutta