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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With