0

Often, I need to a few empty lists (when doing some experiments in ipython that are meant to by tried and forgotten). Is there something elegant way to do:

list1,list2,list3,list4 = [],[],[],[]

I have in mind something like

l1,l2,l3,l4 = *[]

which does not work of course.

sup
  • 680
  • 1
  • 6
  • 17
  • @Brobin, No. All 4 then refer to the SAME object. – Andy Jul 28 '15 at 17:05
  • 1
    Why don't you just make a list of lists, rather than separate names? `lists = [[] for _ in range(4)]`? – jonrsharpe Jul 28 '15 at 17:06
  • `l1, l2, l3, l4 = [[]]*4` EDIT: @Andy is still right... – Aaron Jul 28 '15 at 17:13
  • The answer referred to is clever, but as Alex points out you need to count your left side items for your Range on the right. What happens if you hook up an iterator-based objecton the right? Would it not automatically unpack as many empty lists as desired? – JL Peyret Jul 28 '15 at 17:13
  • @JLPeyret I would think that this wouldn't be possible, as it would not be possible for the number of variables left of an assignment operator in source to ever change. It would always be known how many there are. This functionality would exclusively be useful for interactive testing. – Aaron Jul 28 '15 at 17:17
  • @jonrshape: well, because `peaches` and `oranges` is easier for my head to handle than l[0], l[1]. It is just for throwaway coding when I explore my data. – sup Jul 28 '15 at 17:21
  • Anyway, thanks for the duplicate! – sup Jul 28 '15 at 17:21
  • @Aaron. Well, it might be useful in cases where you want to initialize a bunch of stuff on the left, but not maintain the count on the right. Kind of an edge case, but I tried it to see how iterators would work. They don't help, it seems the assignment "empties" the full iterator at one go, rather than asking a next() one by one (i.e. for each left target). That's on Python 2.7. It's not totally frivolous either, mistakenly sharing mutable references (through a = b = [] or the infamous default function variables) is one of my prime areas of bugs on Python. – JL Peyret Jul 29 '15 at 03:44

0 Answers0