Python Forum
list comprehension invalid syntax - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: list comprehension invalid syntax (/thread-19082.html)



list comprehension invalid syntax - mcgrim - Jun-12-2019

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 ?


RE: list comprehension invalid syntax - Yoriz - Jun-12-2019

a=[x[i].time() for i in range(10)]