Hack Forums
[Python] Python putting List within List when I only want one List - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] Python putting List within List when I only want one List (/showthread.php?tid=5668658)



Python putting List within List when I only want one List - Ineed2learn2eat - Jul 13, 2017

Im fetching a row from a table that has multiple values delimited by a ";". I'm trying to store it within a list. Everything works but instead of python printing it as just ['a','b','c']... it is printing it as [['a','b','c']].

Code below

Code
cur.execute("SELECT * FROM Main_Setup");
rows = cur.fetchall()

job1= []
job2=[]

for row in rows:
    name = row[1]
    fields = row[4].split(';')
    if name == 'File1':
        job1.append(fields)

    elif name == 'file2':
        job2.append(fields)


Output

Code
[['this field', '   another field']]
[['haha', 'no', '  yes']]

Desired Output
Code
['this field', '   another field']
['haha', 'no', '  yes']



* - TheMarkMan - Jul 13, 2017

Try extending, not appending. That should work out
ex: job1.extend(fields)


* - datguy.dev - Jul 13, 2017

You're putting a list into an array... so that's what you'll get doing so. To access the elements you want, you'd have to use jobs2[0]. The len(jobs2) = 1. But len(jobs2[0]) == len(fields).

PHP Code

<?php 
elif name 
== 'file2':
    for 
i in fields:
        
job2.append(i) 



* - Ineed2learn2eat - Jul 13, 2017

(Jul 13, 2017 07:51 AM)TheMarkMan Wrote:  Try extending, not appending. That should work out
ex: job1.extend(fields)

Extending worked! Thank you very much