Home > database >  Simple function cannot modify a list containing just one element
Simple function cannot modify a list containing just one element

Time:02-13

I have a basic function that manipulates a tuple of two-element lists (e.g. (["a","b"],["c","d"])). I also want it to be able to handle a one-element list (e.g. (["a","b"],["c"])).

I tried two solutions which are simple but fail. It looks like the lines of code are being run non-sequentially and causing problems.

The function looks a bit like this:

def example_func(*args):
    text = ([])
    for a in args:
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)

example_func(['Hello', "gobbledy"], ['World', "gook"])
# Correct output --> [('foo:gobbledy', 'Hello'), ('foo:gook', 'World')]
example_func(['Hello', "gobbledy"], ['World', " "])
# Correct output --> [('foo:gobbledy', 'Hello'), ('foo: ', 'World')]

However if I remove gook it will fail, so I tried to make an exception for that...

def example_func(*args):
    text = ([])
    for a in args:
        try:            # Just add a try/except condition
            text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
        except Exception:
            text = ([(f"foo: ", str(a[0])) for a in args])
    print(text)

    example_func(['Hello', "gobbledy"], ['World']) # --> Causes index error

This fails as it runs into an index error. So instead I tried...

def example_func(*args):
    text = ([])
    for a in args:
        if len(a) == 1: # If there's just one element, add a 2nd containing whitespace
            a.append(" ")
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)
example_func(['Hello', "gobbledy"], ['World'])

# This gives an incorrect output:

# [('foo:', 'Hello'), ('foo:', 'World')] --> actual output (fails to print `gobbledy`)
# [('foo:gobbledy', 'Hello'), ('foo:', 'World')] --> desired ouput

So when I was experimenting I tried:

def example_func(*args):
    text = ([])
    for a in args:
        print("a: ", a)
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)

example_func(['Hello', "gobbledy"], ['World', " "]) # Works
example_func(['Hello', "gobbledy"], ['World']) #FAILS, and doesn't even print the second `a`

As the second attempt to run the for-loop fails without printing a: ['World'] as you would expect, it looks like it's running the the comprehension and failing before the print command.

Of course the loop without the comprehension works perfectly. I'm sure it's an elementary mistake in syntax or understanding but I'm really confused.

CodePudding user response:

I think you are overthinking this:

def example_func(*args):
    text = []
    for a in args:
        if len(a) == 1:
            text.append( ("foo:",a[0]) )
        else:
            text.append( (f"foo:{a[1]}", a[0]) )
    print(text)

example_func(['Hello', "gobbledy"], ['World', " "]) # Works
example_func(['Hello', "gobbledy"], ['World'])

Output:

[('foo:gobbledy', 'Hello'), ('foo: ', 'World')]
[('foo:gobbledy', 'Hello'), ('foo:', 'World')]
  • Related