Home > Back-end >  Replace list element with class instance
Replace list element with class instance

Time:04-07

I have a class that transforms list like [1, 2] into symbols. It take 2 positional arguments that correspond to each of the elements in the list. I am making another function that takes in argument a list such as this one:

lst = [[1,2], None, [1,1]]

and transforms it into a list that has the symbols ◇ ◯ instead of the sublists. I made this code to do this but it tells me that list indices must be integers, not list.

newlist = [SymbolClass(l[l][0],l[l][1]) if l is not None else l for l in lst]

How should I change my code to make it work?

CodePudding user response:

You are trying to index the list using l, but l is a list element, not an index. Try

newlist = [SymbolClass(l[l][0],l[l][1]) if l is not None else l for l in range(len(lst))]

By the way, l is a not such a great single-character variable name, since it often looks like number 1.

However, there's no need to use an explicit index. A cleaner way to write this would be

newlist = [SymbolClass(x[0],x[1]) if x is not None else x for x in lst]
  • Related