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,669
  • 4
  • 35
  • 67
nos
  • 18,322
  • 27
  • 89
  • 126

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,903
  • 16
  • 16
0
y=list(x)

The above one should work fine

Teja
  • 12,590
  • 31
  • 87
  • 147
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
  • 49,771
  • 9
  • 103
  • 112