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?

dawg
  • 90,796
  • 20
  • 120
  • 197
Joel
  • 99
  • 5
  • It works fine when I run it. – Ryan Mar 11 '18 at 17:24
  • 1
    Possible duplicate of [What is the pythonic way to detect the last element in a python 'for' loop?](https://stackoverflow.com/questions/1630320/what-is-the-pythonic-way-to-detect-the-last-element-in-a-python-for-loop) – Abdul Niyas P M Mar 11 '18 at 17:26

5 Answers5

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.

Pam
  • 1,106
  • 1
  • 15
  • 17
  • 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! – Farstride Mar 11 '18 at 19:06
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.
dawg
  • 90,796
  • 20
  • 120
  • 197
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'>                                               
'''
Austin
  • 25,142
  • 4
  • 21
  • 46
  • 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 Mar 11 '18 at 19:25
  • @Pam thank you. I find yours the best of the five and should have been accepted as answer. Happy coding! – Austin Mar 12 '18 at 02:12
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))
Ryan
  • 123
  • 3
  • 12
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))
Jon Reinhold
  • 189
  • 1
  • 9