Computer Science, asked by mdnizamulkhan5152, 4 months ago

Write a program to find and change all even numbers in a list by adding 2 and all odd numbers

by subtracting 2.
( L=[2, 5, 12, 14, 23, 45] ) ​

Answers

Answered by Oreki
1

\textsf{\large One-Liner}

   \texttt{print(\[[i + 2 if i \% 2 == 0 else i - 2 for i in \[[2, 5, 12, 23, 45\]]\]])}

\textsf{\large Detailed}

   \texttt{original\_list, modified\_list = \[[2, 5, 12, 23, 45\]], \[[\]]}\\\texttt{for element in original\_list:}\\\texttt{\hspace{1em} if element \% 2 == 0:}\\\texttt{\hspace{2em} modified\_list.append(element + 2)}\\\texttt{\hspace{1em} else:}\\\texttt{\hspace{2em} modified\_list.append(element - 2)}\\\texttt{print(modified\_list)}

Attachments:
Similar questions