2

I am trying to write a function that will take a list of lists and print them out one by one with the word UNION between them. My code looks like this:

def printsql(lst):
    print("INSERT INTO table")
    for x in lst:
        print("SELECT")
        print(*x, sep=', ')
        print("UNION")
    return(str)

a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]

print(printsql(a))

My output currently looks like this:

INSERT INTO table
SELECT
1, 3, 4
UNION
SELECT
2, 5, 7
UNION
SELECT
3, 4, 6
UNION

This is almost exactly what I need but I can't figure out how to not print the last "UNION". Can someone advise?

2
  • It works fine when I run it. Commented Mar 11, 2018 at 17:24
  • Aside from this being a duplicate, return(str) in this code makes absolutely no sense, and neither does the print in print(printsql(a)). Commented Mar 29, 2023 at 7:43

5 Answers 5

3

The brute force is to use enumerate

for idx, x in enumerate(lst):
  #other stuff#
  if idx<(len(lst) - 1):
    print("UNION")

But I’d be interested to see if there is a more elegant solution.

Sign up to request clarification or add additional context in comments.

1 Comment

I think adding a repeating pattern at the front of strings just screams .join() like dwag did, but I find this answer to be more readable and simple! Good stuff!
2

Consider using the .join method in Python to insert a string between list elements.

Works like so:

>>> '|'.join(['a','b','c','d'])
'a|b|c|d'

Your example is essentially doing this:

[Header string "INSERT INTO table\nSELECT\n"]
'\nUNION\nSELECT\n'.join([list items])
', '.join([sub list items])

To get the pattern you describe.

You can take that description and translate to Python:

def printsql(lst):
    s="INSERT INTO table\nSELECT\n"
    s+="\nUNION\nSELECT\n".join(', '.join(str(e) for e in sl) for sl in lst)
    return s

Then:

>>> a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]
>>> print(printsql(a))
INSERT INTO table
SELECT
1, 3, 4
UNION
SELECT
2, 5, 7
UNION
SELECT
3, 4, 6

The general outline is:

  1. Create the header with s="INSERT INTO table\nSELECT\n";
  2. Use a nested join to create the list of lists format of "\nUNION\nSELECT\n" between the outer list elements and ', ' with the inner list elements;
  3. Return the string to be printed or used in another section of the program.

Comments

1

This will remove the last union and class str

   def printsql(lst):
        print("INSERT INTO table")
        counter = 0
        for x in lst:
                counter = counter + 1
                print("SELECT")
                print(*x, sep=', ')
                if (len(lst)- 1) > counter:
                        print("UNION")
        return("")

a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]

print(printsql(a))

5 Comments

This is a quick and easy solution.
Awesome, Thanks so much
Why the return(str)? When you print the returned value you get <class 'str'> from an empty str object.
I fix the class "str" return value can you remove your down vote to the code now.
Well, enumerate is more elegant than counter, but this works fine, too!
1

This is one way avoiding an extra looping and condition:

def printsql(lst):
    print("INSERT INTO table")
    for x in lst[:-1]:
        print("SELECT")
        print(*x, sep=', ')
        print("UNION")
    print("SELECT")
    print(*lst[-1], sep=', ')
    return(str)

a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]

print(printsql(a))

'''
INSERT INTO table
SELECT                                                      
1, 3, 4                                                     
UNION                                                      
SELECT                                                      
2, 5, 7                                                     
UNION                                                       
SELECT                                                     
3, 4, 6                                                    
<class 'str'>                                               
'''

2 Comments

That’s elegant and readable! Dawg's answer is also good, but I find the python style of putting loads of things on one line difficult to follow/generate.
@Pam thank you. I find yours the best of the five and should have been accepted as answer. Happy coding!
0

Quick and dirty.

def printsql(lst):
    print("INSERT INTO table")
    for x in lst:
            if x != lst[-1]:
                 print("SELECT")
                 print(*x, sep=', ')
                 print("UNION")
            else:
                print("SELECT")
                print(*x, sep=', ')

    return(str)

a = [[1, 3, 4], [2, 5, 7], [3, 4, 6]]

print(printsql(a))

2 Comments

Does this assume a list of unique strings? That is, if all the strings in the list are identical, will it work?
It assume the final value is unique. Safer route would be if x is lst[-1]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.