Handle either a list or single integer as an argument

Question:

A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly.

This is what I have now, but ideally there wouldn’t be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:

def select_rows(to_select):
    # For a list
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)
    # For a single integer
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() == to_select:
            table.selectRow(row)
Asked By: Steven Hepting

||

Answers:

I would do just this:

def select_rows(to_select):
    # For a list
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)

and expect that the argument will always be a list – even if its just a list of one element.

Remember:

It is easier to ask for forgiveness than permission.

Answered By: Andrew Hare

You could redefine your function to take any number of arguments, like this:

def select_rows(*arguments):
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in arguments:
            table.selectRow(row)

Then you can pass a single argument like this:

select_rows('abc')

multiple arguments like this:

select_rows('abc', 'def')

And if you already have a list:

items = ['abc', 'def']
select_rows(*items)
Answered By: Steef

Actually I agree with Andrew Hare’s answer, just pass a list with a single element.

But if you really must accept a non-list, how about just turning it into a list in that case?

def select_rows(to_select):
    if type(to_select) is not list: to_select = [ to_select ]

    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)

The performance penalty for doing ‘in’ on a single-item list isn’t likely to be high 🙂
But that does point out one other thing you might want to consider doing if your ‘to_select’ list may be long: consider casting it to a set so that lookups are more efficient.

def select_rows(to_select):
    if type(to_select) is list: to_select = set( to_select )
    elif type(to_select) is not set: to_select = set( [to_select] )

    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)
Answered By: NickZoic

I’d go along with Sharkey’s version, but use a bit more duck typing:

def select_rows(to_select):
    try:
        len(to_select)
    except TypeError:
        to_select = [to_select]

    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)

This has the benefit of working with any object that supports the in operator. Also, the previous version, if given a tuple or some other sequence, would just wrap it in a list. The downside is that there is some performance penalty for using exception handling.

Answered By: DopplerShift

A simple wrapper could do, to handle list or single object case

  def wrap_list(val):
    if type(val) is list:
      return val
    return [val] 
Answered By: FlashDD

A bit less general but concise, using numpy:

numpy.unique()

handles that automatically by keeping only the unique values of an array-like or scalar, and returns a list of the unique values, or of the scalar.

import numpy as np

def select_rows(to_select):
   to_select = np.unique(to_select)

   for row in range(0, table.numRows()):
       if _table.item(row, 1).text() in to_select:
           table.selectRow(row)
Answered By: Paul Lebaigue
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.