Search code examples
pythonlistgeneratorcreation

python list creation including generator and non_generator


Seems like there should be an easier way to do this:

header_line = [x for x in my_dict.keys()]
header_line.insert(0, "1st column\t2nd column")
header_line.append("note")
print "\t".join(map(str, header_line))

naively i thought the following should work, but get syntax error on the header_line:

header_line = ["1st column", "2nd column", x for x in my_dict.keys(), "note"] 
print "\t".join(map(str, header_line))

Solution

  • How about

    header_line = ['1st column', '2nd column'] + [x for x in my_dict.keys()] + ['note']
    

    As mentioned in the comments, for this case you can just use my_dict.keys() or list(my_dict), but the above example is still useful as an example of how to do this when the list comprehension can't be trivially eliminated.