Computer Science, asked by mdnizamulkhan5152, 6 months ago

Write a (PYTHON) 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 anindyaadhikari13
7

Answer:

This is the required python program for the question.

L=[2, 5, 12, 14, 23, 45]

print("List Before: ",L)

for i in range(len(L)):

if L[i]%2==0:

L[i]+=2

else:

L[i]-=2

print("List After: ",L)

Algorithm:

  1. START.
  2. Initialise L=[2, 5, 12, 14, 23, 45]
  3. Iterate a loop through the list.
  4. Check if the list element is odd or not. If odd, subtract 2 or else, add 2.
  5. Display the list.
  6. STOP.

See the attachment for output .

Attachments:
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