-3

I have a piece of code that does this:

def number(self, width = None):

        if not self.v:
            return None

        if not width:
            width = len(self.v)

        return self.VERSION_DELIMITER.join(map(str, self.v[:width]))

I recently changed to using Python 3 instead of 2. When I did that I started getting the error:

TypeError: 'map' object is not subscriptable:

What is the best way to make this work in Python 3?

shafi97
  • 21
  • 1
  • 5
  • Can you share an example of the values of `self.v` and `width` and the output you're expecting to get for these values? – Mureinik Nov 02 '20 at 22:40
  • Please edit your question to include a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Jasmijn Nov 02 '20 at 22:42

1 Answers1

0

self.v is a map object, which are not subscriptable in Python 3. The easiest fix is to make it into a list before slicing:

map(str, list(self.v)[:width])

Depending on the rest of class implementation, it might be better to explicitly store .v as a list

Marat
  • 15,215
  • 2
  • 39
  • 48
  • 2
    Another way is to use `islice`: add the line `from itertools import islice` and then you can use `map(str, islice(self.v, width))`. This doesn't construct two temporary lists. – Jasmijn Nov 02 '20 at 22:46
  • @Jasmijn that's definitely a better approach, can't believe I didn't know about this function. Would you mind posting it as an answer (I'll delete mine)? – Marat Nov 02 '20 at 22:48
  • @Marat this makes sense! Thanks – shafi97 Nov 02 '20 at 22:48
  • 1
    This won't work. `list(self.v)` will exhaust the `map` object the first time through, so it will be empty the next time. You're better off saving it as a list right away. The dupe I linked to goes over different options. – Carcigenicate Nov 02 '20 at 22:49