0

I try to use the map() function to set items of a qtablewidget in this way:

x,y = np.meshgrid(range(5),range(10))
map(lambda x,y: self.tab.setItem(x,y,QTableWidgetItem()), x,y)

but it is not working, items are not set whereas I have no error. Any idea on what is wrong ?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
lelorrain7
  • 315
  • 5
  • 13

1 Answers1

1

As the documentation of map() explains, it returns an iterator (as opposed to the behavior on Python 2 which called the function in place).

This means that the function will not be called until the returned map object is iterated.

A possible solution would be to "force" the iteration by converting it to a list:

list(map(lambda x, y: self.tab.setItem(x, y, QTableWidgetItem()), x, y))

Which is roughly the same as:

[self.tab.setItem(x, y, QTableWidgetItem()) for x, y in zip(x, y)]

That said, consider that such usage of mapping or comprehensions is usually frown upon, as they do not really provide any benefit:

  • there's no performance increase (on the contrary, you're creating a map object and then a list from it);[1]
  • it makes debugging more difficult;
  • it makes the code much less readable (and that's very important);

There are very few situations for which using an approach like this is actually required, and a for loop is almost always a better choice.

[1] list comprehensions offer performance benefits as they actually build the list object after all elements have been gathered, while using list.append() continuously grows the existing list object (see this answer), but since you're not creating a list that will be actually used, those benefits are completely nullified, and a for loop is a clearer, better and faster choice.

musicamante
  • 41,230
  • 6
  • 33
  • 58