Reputation: 1889
I have list seeds and leechs which return 19 on asking length using len()
And using these two lists is a list comprehension -
sldiff = [(int(seed)-int(leech)) for seed in seeds for leech in leechs]
Each element is supposed to be the difference between the seed and leech(which are strings so have to be typecasted)
But len(sldiff)
returns 361!
My questions are - Why is it happening and what should I do to get required sldiff list?
Upvotes: 1
Views: 160
Reputation: 15367
You get the result of 19 * 19 = 361 because of the two for loops.
I'm not exactly sure what you want but probably something like:
sldiff = [int(seed[x]) - int(leech[x]) for x in xrange(len(seeds))]
Assuming that len(seeds) == len(leechs)
Upvotes: 1
Reputation: 8620
[(int(seed)-int(leech)) for seed in seeds for leech in leechs]
is similiar as:
temp = []
for seed in seeds:
for leech in leechs:
temp.append(int(seed)-int(leech))
Apparently it is 19 * 19.
I think you want
[int(x)-int(y) for x, y in zip(seeds, leechs)]
Upvotes: 2
Reputation: 600041
You're doing a double list comprehension - ie you're iterating through the whole of 'seeds' for each entry in 'leechs' (so 19*19, ie 361).
Seems like what you actually want to do is iterate through one list, each entry of which is a combination of the relevant entry from seeds and the one from leechs. That is what zip
does:
[(int(seed) - int(leech)) for seed, leech in zip(seeds, leechs)]
Upvotes: 3