-2

I have an existing tuple containing two list:

list_a = [1, 2, 3]
list_b = [4, 5, 6]

tuple = list_a, list_b
tuple = ([1, 2, 3], [4, 5, 6])

How do I add another list to this tuple without creating a tuple in the tuple containing the first two lists?

list_c = [7, 8, 9]

#Code to add list_c to tuple

tuple = ([1, 2, 3], [4, 5, 6], [7, 8, 9])
Linus Wagner
  • 151
  • 1
  • 1
  • 8
  • 6
    Tuples are immutable... why can't you use a list? – G_M Jun 26 '17 at 19:19
  • 2
    Also, don't name your tuple *tuple*, as it shadows the built-in *tuple*. – idjaw Jun 26 '17 at 19:22
  • @DeliriousLettuce Only where reassignments are concerned. You can still add two together. – cs95 Jun 26 '17 at 19:23
  • @Coldspeed I thought adding two tuples together creates a new tuple. It doesn't seem to modify the original. `>>> a = (1, 2) >>> id(a) 140559292145464 >>> a += (3, 4) >>> id(a) 140559292436248` – G_M Jun 26 '17 at 19:27
  • No, I was just trying to say that their immutability is irrelevant here. :) – cs95 Jun 26 '17 at 19:28
  • @Coldspeed It is the definition of relevant here. "How do I add another list to this tuple..." – G_M Jun 26 '17 at 19:29
  • I don't think OP is concerned as to whether the original is modified or not... hard to say without more clarification... OP seems to have disappeared. – cs95 Jun 26 '17 at 19:38
  • 1
    @JasonStein for future reference, it is better if you mark duplicates using the *Flag* option on the question and selecting Mark as Duplicate. This will automatically post a comment on your behalf linking to the original question – DarkCygnus Jun 26 '17 at 19:54

3 Answers3

5

Firstly, it is a bad idea to use tuple as a variable name.

Secondly, tuples are immutable, i.e you cannot change an existing tuple. So what you can do is, create a new tuple and assign the existing value.

list_a = [1, 2, 3]
list_b = [4, 5, 6]

tuple1 = list_a, list_b

list_c = [7, 8, 9]
tuple2 = tuple1 + (list_c,)

thus, tuple2 is the final tuple that you need. Hope this helps!

rowana
  • 718
  • 2
  • 8
  • 21
4

You can wrap your 3rd list inside a singleton tuple and then add it to the existing one:

list_a = [1, 2, 3]
list_b = [4, 5, 6]

tuple1 = list_a, list_b    
tuple1 += ([7, 8, 9],)

print(tuple1)

Output:

([1, 2, 3], [4, 5, 6], [7, 8, 9])

Also, I'd advise against using tuple as a variable name, especially when working with tuples...

cs95
  • 379,657
  • 97
  • 704
  • 746
2

tuple = tuple + (list_c,)

Is there a particular reason you are using a tuple of lists, rather than a list of lists? Tuples are immutable and reassigning / remaking at every step is much more expensive than list.append().

Jason Stein
  • 714
  • 3
  • 10