0

There are 2 cases in my function, 1: All arguments will be strings there is no problem with this one. 2: There will also be int or floats. What i want to do is, check the types of *vars, if there is int or float type, find the index of this types.

def fonk(comp, *vars):
    varList = []
    varList.append(vars)
    varList = [x for xs in varList for x in xs]
    for i in range(len(varList)):
       if all(isinstance(x, str) for x in varList) == False:
          if type(varList[i]) == int or float:

for example:

fonk(">","str1", 1, "str2", 2.5)

so int and float type would be vars[1] and vars[3]. How can i determine this? Thanks in advance.

python101
  • 11
  • 3
  • Why are you nesting `vars` inside another list in `varList`, then flattening it with the list comprehension? You're just doing `varList = vars.copy()` – Barmar Jan 13 '22 at 08:25

2 Answers2

0

To check type you want to check each separately and do the operation according to the type.

def fonk(comp, *vars):
    for var in vars:
        if isinstance(var, str):
            pass
        elif isinstance(var, (int, float)):
            pass
MYousefi
  • 978
  • 1
  • 5
  • 10
  • The thing is i want to use that specific index. For example fonk("<", 1, 2.5, "3", 4 ), which means vars[0] and vars[3] are int. So i want to use something like vars[x], x corresponds to type(int) and i will assign that to another variable or sth. later on. return [i for i, val in enumerate(vars) if isinstance(val, (int, float))] this returns which indices are int or float however how can i place them into vars[x] or sth like that. – python101 Jan 13 '22 at 14:22
  • You'd have to process vars and make a new list out of them. You can't replace the vars from the function. `*vars` is an iterator that python makes for you on the fly. You can only process it and make a list out of it. – MYousefi Jan 13 '22 at 19:38
0
def fonk(comp, *vars):
    if not all(isinstance(x, str) for x in varList):
        return [i for i, val in enumerate(vars) if isinstance(val, (int, float))]

There's no need to copy vars to varList, and the all() test should not be inside a loop.

if type(varList[i]) == int or float:

is not the correct way to test if something is equal to one of multiple values. See Why does "a == x or y or z" always evaluate to True?

You can give isinstance() a tuple of types, and it will test if it's an instance of any of them.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • *vars is being formed up as tuple and the simulation program that i am using is looking for arrays so i tried to convert tuple into array. Thanks for the answer that's what i was looking for but also, how can i use the index accordingly. I mean like: varList[x] where x corresponds to type(int). – python101 Jan 13 '22 at 11:20
  • When this returns a list, you can use `varList[i] for i in fonk(comp, *varList)` – Barmar Jan 13 '22 at 15:11