-3

I have a list of lists, like

outlist = (['d1', 'd2', 'd3'], ['d4', 'd5', 'd6'])

I want to append ['d7', 'd8', 'd9'] to the above list

outlist.append(['d7', 'd8', 'd9']) gives me error

Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    outlist.append(['d7','d8','d9'])
AttributeError: 'tuple' object has no attribute 'append'

outlist.insert(['d7', 'd8', 'd9']) also gives me an error

Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    outlist.insert(['d7','d8','d9'])
AttributeError: 'tuple' object has no attribute 'insert'

Need help in resolving this. I would also want to write the 'outlist' to a csv file. How do I do that?

mickey
  • 23
  • 1
  • 1
  • 4
  • 2
    what you have is not a "list of lists", it's a "tuple" of lists. As the error suggests. So you need to use a list instead of a tuple if you want to append to it. – mavili Aug 16 '13 at 09:06

4 Answers4

2

You have a tuple, not a list, and those are immutable.

Use concatenation if you want to alter the tuple, adding another tuple with elements:

outlist += (['d7','d8','d9'],)

Here you re-bind outlist to a new tuple that is the concatenation of the original value plus a tuple of length one. You can omit the parenthesis even:

outlist += ['d7','d8','d9'],

as it is the comma that makes the expression on the right a tuple.

The alternative is to turn your tuple into a list with the list() type first:

outlist = list(outlist)

and now you can call .append() and .insert() at will.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1
AttributeError: 'tuple' object has no attribute ...

That is not a list, that is a tuple. Tuples are immutable, therefore there is no way to do what you want. Convert it to a mutable sequence first.

outlist = list(outlist)

Or create it as a list in the first place.

(And next time, spend a few moments reading the error message first.)

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

It's not a list of lists, it's a tuple containing two lists. Tuples are immutable in Python. Change the first line to:

outlist = [['d1', 'd2', 'd3'], ['d4', 'd5', 'd6']]
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
0

Tuples are immutable in Python. Convert outlist to list if you want to add an item:

>>> outlist = (['d1', 'd2', 'd3'], ['d4', 'd5', 'd6'])
>>> outlist = list(outlist)
>>> outlist.append(['d7', 'd8', 'd9'])
>>> outlist
[['d1', 'd2', 'd3'], ['d4', 'd5', 'd6'], ['d7', 'd8', 'd9']]
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195