1

I need to make a copy of a list from a list of lists. The following code gives an error message:

y = list[x]
TypeError: unsubscriptable object
a = [[0],[1]]
for x in a:
    y = list[x]
    print y

What am I doing wrong here?

HaskellElephant
  • 9,819
  • 4
  • 38
  • 67
nos
  • 19,875
  • 27
  • 98
  • 134

3 Answers3

4
y = list[x]

Are you sure you aren't meaning to call the list constructor with the variable x as a parameter, instead of trying to access the element 'x' in the variable 'list'? As in:

y = list(x)
veiset
  • 1,973
  • 16
  • 16
0
y=list(x)

The above one should work fine

Teja
  • 13,214
  • 36
  • 93
  • 155
0

list is actually the type, so it makes no sense to try and get its x element. If you want to instantiate a list, you need to use list(iterable).

Now, if you want to copy a list, the simpler solution would be to use the copy module.

import copy
a = [[0],[1]]
new_list = copy.copy(a[0])

Pay attention to the fact that if you want to copy an item with nested elements, you'll have to use copy.deepcopy.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116