Using list of rows whether I have 1 row or N many

311 views Asked by At

I have

foo=("bob","smith","123")

and sometimes

foo=(("bob","smith","123"),("sam","smith","124"))

and a for loop:

for rows in foo:

But I want the for loop to treat foo as a list of rows even if it just one row inside it instead of n many. Right now if I only get passed in the 1st foo, it will iterate by bob, smith, 123 but if I pass the 2nd foo it will iterate by rows (which is what I want). The objects are pyodbc.Row.

Another way of saying this is that I want to be able to use:

foo[0][1]=stuff

If I am passed many rows, or just one.

How can I do this?

4

There are 4 answers

1
Bas Swinckels On BEST ANSWER

A trick I use often inside a function that accepts different types of inputs is to first normalize the uncommon input to the common type, and then handle the common type. Similarly, in your case you could do something like (untested):

if not isinstance(foo[0], tuple):  # only a single row
    foo = (foo,)  # add row to tuple of lenght 1 
for row in foo:  # now we are sure foo is a tuple of rows
    # do something with row
2
deathangel908 On

You definitely need an extra check, because strings are also iterable. So why don't you just use a specific format for your list?

foo=(("bob",),("smith",),("123",))

Well you can also check the type to get an element. Or if you insist:

# foo = ("bob", "smith", "123")
foo=(("bob","smith","123"),("sam","smith","124"))
for rows in foo:
    a = rows if isinstance(rows, tuple) else (rows,)
    print (a[0])
0
skynyrd On

Why don't you prefer using:

foo=(("bob","smith","123"),)

then

for row in foo:
    DoSomething(row[0])
0
Nizam Mohamed On

Use if expression in for.

for rows in (foo,) if type(foo[0]) is not tuple else foo:
    print(rows)