I am in the process of learning list comprehensions and stumbled into a type of problem that I cannot find resources to adequately understand.
The problem stems from the following question: We have an Array [1,2,3,8,9] and want to create an expression that would return each odd number twice, while even numbers are only returned once.
Note: there's also a hint that I could create nested lists but that so far has not helped me pinpoint how that would serve me.
The output of the appropriate algorithm should be: [1,1,2,3,3,8,9,9]
Using a loop, I could do what I want like this:
OtherNumList = [1, 2, 3, 8, 9]
OtherNumList2 = []
for i in OtherNumList:
if i%2==1:
OtherNumList2.append(i)
OtherNumList2.append(i)
else:
OtherNumList2.append(i)
print(OtherNumList2)
I want to do this using just an expression, or otherwise "one-line" it using a list comprehension.
I'm struggling with understanding how to set the comprehension to append twice if X while appending once if Y.
I'd appreciate your help with understanding even just the concept of building the comprehension; I do not expect a spoon-fed solution, and would rather prefer it if you could walk me through your thinking process so that I can better set my own foundations for better list comprehensions in the future! :)