Python Forum

Full Version: What does ty(val) mean?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In the following code:
>>> line='yosi, 1, 3.14'
>>> types=[str, int, float]
>>> raw=line.split(',')
>>> raw
['yosi', ' 1', ' 3.14']
>>> fields = [ty(val) for ty,val in zip(types,raw)]
>>> fields
['yosi', 1, 3.14]
What do ty and val refer to?
zip(types,raw) create an iterator that produces tuples of the form (x, y)
>>> >>> list(zip(types,raw))
[(<class 'str'>, 'yosi'), (<class 'int'>, ' 1'), (<class 'float'>, ' 3.14')]
>>> for ty,val in zip(types,raw):
...   print("ty:",ty,"val:",str(val))
...
ty: <class 'str'> val: yosi
ty: <class 'int'> val:  1
ty: <class 'float'> val:  3.14
zip(types, raw) will yield 2-element tuples, where each tuple element at index 0 comes from types list and element at index 1 comes from raw list.
Then you unzip each tuple into 2 names - ty and val.
Then you use the function ty to convert val (which is initially str) to respective type.