0

to all, I was doing some searches on the use of list comprehension syntax. I would like to see if it's possible to return 2 lists from 2 existing lists with 1 line of code i.e using list comprehension. I came across this post Possible to return two lists from a list comprehension? which make me think it's possible. Creating the new lists independently works fine I would like to see how far I can take it i.e minimal code but still easily readable

Consider the following I have 2 pre-existing lists wnv and wdv and would like to create 2 new lists Av and Bv as follows;

Av,Bv=[(zeta*wn*dt,wd*dt) for i,(wn,wd) in zip(wnv,wdv)]

where zeta and dt are just a numbers Can this be done? With the above code, I am getting the error: unpack non-iterable float object

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
JXB
  • 29
  • 5
  • Can you show the structure of `wnv`, `wdv` and how you're doing it without list comprehension? – A.J. Uppal Apr 19 '20 at 07:20
  • 1
    Are both lists of the same length? What would you like to happen if the lists are of different lengths? – cup Apr 19 '20 at 07:21
  • Isn't the link that you shared wholly answer your question? – Austin Apr 19 '20 at 07:21
  • 1. Now that I see the addition of the zip() at the beginning of the line the link make sense. 2. The lists will always be the same length as they "emanate" from 1 list. 3. I had For ... loop on the "master" list in in which I calculate a number of variables on the fly, then I tested 1 line of code using list comprehension approach per list desired and finally realised that maybe I could create some of the lists using 1 line of code. I have no tested if the "1-line" approach is actually faster – JXB Apr 19 '20 at 07:34

2 Answers2

2

You're close, you just have to unzip the result at the end :

Av,Bv = zip(*[(zeta*wn*dt,wd*dt) for (wn,wd) in zip(wnv,wdv)])

(and remove the i from your code)

jpl
  • 367
  • 2
  • 11
0

The error shows up as the zip creates a list of Tuples (each having 2 elements) which is iterated over. Here, only the tuple (wn, wd) is taken from the list that is being iterated and not the variable i.

The following code should work well:

Av,Bv = zip(*[(zeta*wn*dt,wd*dt) for (wn,wd) in zip(wnv,wdv)])

PS, note that the end results Av and Bv are actually tuples and not lists.

Anirudh
  • 11
  • 2
  • The data in Av and Bv are "frozen" for the calculation so tuples are probably OK. Can you have produce list rather than tuple however? – JXB Apr 19 '20 at 08:01
  • You can use the list() method to convert the tuple into a list. This method can moreover be used on lists(obviously), tuples, sets and dictionaries(where it returns a list of keys) – Anirudh Apr 19 '20 at 08:38
  • to close the question. Tested a master list with 200,000 elements. using list comprehension syntax, creating 8 lists in (3 x 2 lists 1-go and 3 lists in 1-go takes 1.113seconds. Creating 8 lists one a time takes 0.771 seconds – JXB Apr 19 '20 at 12:53