Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace list element with class instance

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading