Python Forum

Full Version: list comprehension invalid syntax
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
the list comprehension in this code (see last line)

import datetime 
from datetime import timezone
from datetime import timedelta
from datetime import time
import matplotlib.dates as dates

customdate = datetime.datetime(2016, 1, 1, 13, 30)
y = [ 2,4,6,8,10,12,14,16,18,20 ]
x = [customdate + datetime.timedelta(hours=i) for i in range(len(y))]


a=x[i for i in range(10)].time()
gives me this error

Error:
runfile('C:/Users/Desktop/python ode/hours.py', wdir='C:/Users/Desktop/python ode') Traceback (most recent call last): File "C:\Users\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2961, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-1003-532af0fdc54e>", line 1, in <module> runfile('C:/Users/Desktop/python ode/hours.py', wdir='C:/Users/Desktop/python ode') File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile execfile(filename, namespace) File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Desktop/python ode/hours.py", line 28 a=x[i for i in range(10)].time() ^ SyntaxError: invalid syntax
I am trying to print all those values in range 10, which it works with a regular for loop, but
when I want to recall them out of the loop, only one value is printed

customdate = datetime.datetime(2016, 1, 1, 13, 30)
y = [ 2,4,6,8,10,12,14,16,18,20 ]
x = [customdate + datetime.timedelta(hours=i) for i in range(len(y))]

for i in range(10):
    a=x[i].time() 
    print(a)   #prints all values
    
customdate = datetime.datetime(2016, 1, 1, 13, 30)
y = [ 2,4,6,8,10,12,14,16,18,20 ]
x = [customdate + datetime.timedelta(hours=i) for i in range(len(y))]

for i in range(10):
    a=x[i].time() 
    
    
print(a)  # only one value is printed
so, how do I print all of the values by staying out of the for loop ?
a=[x[i].time() for i in range(10)]