List Comprehension Version Of "extend"
Is there a 1-liner equivalent (using list comprehension) for the following: a = [] for i in range(6): a.extend(((-i,i,0,2),(-i-1,i,0,6))) a = tuple(a) I was thinking something
Solution 1:
You can use a nested list comprehension.
>>>[t for i inrange(6) for t in ((-i,i,0,2), (-i-1,i,0,6))]>>>
[(0, 0, 0, 2),
(-1, 0, 0, 6),
(-1, 1, 0, 2),
(-2, 1, 0, 6),
(-2, 2, 0, 2),
(-3, 2, 0, 6),
(-3, 3, 0, 2),
(-4, 3, 0, 6),
(-4, 4, 0, 2),
(-5, 4, 0, 6),
(-5, 5, 0, 2),
(-6, 5, 0, 6)]
It reads like this
[what I want (t) | forloopsasif writing non-listcomp code]
and is thus equivalent to
result = []
for i in range(6):
for t in ((-i,i,0,2), (-i-1,i,0,6)):
result.append(t)
Post a Comment for "List Comprehension Version Of "extend""