0

P/S:This is not duplicate, I already have an answer myself which map to the answer in the duplicated solution, what I need is the shortest expression that is possible.

l=[set()]*passwordLen
l[0].add(1)
print l

will give result

[set([1]), set([1]), set([1]), set([1]), set([1]), set([1])]

but I need

[set([1]), set(), set(), set(), set(), set()]

what is the shortest expression to create list of sets that could achieve this?

what I could think of is

l=[set() for _ in xrange(passwordLen)]
l[0].add(1)
print l
william007
  • 17,375
  • 25
  • 118
  • 194
  • So... what is the problem with what you already have? – jonrsharpe Oct 19 '14 at 09:21
  • @jonrsharpe possibility of a shorter expression than `l=[set() for _ in xrange(passwordLen)]` – william007 Oct 19 '14 at 09:22
  • 2
    You could make it one line with `l = [set() if x else set([1]) for x in xrange(passwordLen)]`, but really I suggest you just stick with what you have (which is simple and readable) and don't waste time trying to golf it. – jonrsharpe Oct 19 '14 at 09:25
  • 1
    Could you tell us *why* you want the expression to be shorter? That is, what problem is solved with having a shorter expression? – Robᵩ Oct 19 '14 at 10:34

1 Answers1

1

I don't know if this is the shortest, but it's shorter than your:

l=map(set,[[]]*passwordLen)

Example

>>> l[0].add(1)
>>> print l
[set([1]), set(), set(), set(), set(), set()]
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115