简体   繁体   中英

Tuple comparison in function

I am wondering why my comparison returns False and not True although 'a' == 'a' .

def test(*values):
    return values[0]=='a'

tuple = ('a',)
test(tuple)

Output: False

Using the *args syntax in the function declaration means that all parameters will be collected into a new tuple. When you pass your tuple now to this function, it will create a tuple with only one element since you passed only one argument. The value of values is (('a',),) a tuple with tuple in it. What you probably meant to do was to spread the tuple into the function call which involves the same asterisk syntax: test(*tuple) which results in values == ('a',) as you expected.

It's because you are using *values rather than values in your function definition

When you use the special syntax *args in a function, args will already come back as a tuple, where each arg is an element of the tuple.

So for example

> def print_args(*args):
    print(args)
> print_args('a', 'b', 'c')

# Outputs:
('a', 'b', 'c')

In your case since you are passing in a tuple already, w/in the functions values is like "Ok, I'll happily take a tuple as my first argument", and values becomes a tuple of tuples (well a tuple of a single tuple). Thus you are comparing ('a',) to 'a' and your check fails

TL;DR: either pass in just 'a' or change *values to values

def test(values):
    return values[0] == 'a'

tuple = ('a',)
test(tuple)

# Outputs:
True

Modify your function like this:

def f(*v):
    print(v)
    return v[0] == 'a'

then call f(('a',)), you'll get (('a',),) False function gets a tuple ('a',) not 'a'

quote

def func(*args, **kwargs): ... var-keyword: specifies that arbitrarily many keyword arguments can be provided (in addition to any keyword arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with **, for example kwargs in the example above.

https://docs.python.org/3/glossary.html#term-parameter

your not passing a pointer to the type using *args. the parser thinks your passing keyword arguments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM