1.
Python Program to Swap Two Elements in a List
a = [10, 20, 30, 40, 50]
a[0], a[4] = a[4], a[0]
print(a)
………………………………
temp = a[2]
a[2] = a[4]
a[4] = temp
print(a)
2. Python Program to Count Even and Odd Numbers in a List
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even = 0
odd = 0
for num in a:
if num % 2 == 0:
even += 1
else:
odd += 1
# Printing the results
print("Even numbers:", even)
print("Odd numbers:", odd)
to print positive numbers in a list
a = [-10, 15, 0, 20, -5, 30, -2]
for val in a:
if val > 0:
print(val)
to print negative numbers in a list
a = [5, -3, 7, -1, 2, -9, 4]
for num in a:
if num < 0:
print(num)
to count positive and negative numbers in a list
a = [10, -20, 30, -40, 50, -60, 0]
pos = 0
neg = 0
for n in a:
if n > 0:
pos += 1
elif n < 0:
neg += 1
print(pos)
print(neg)
Remove multiple elements from a list
a = [10, 20, 30, 40, 50, 60, 70]
# Elements to remove
remove = [20, 40, 60]
# Remove elements using a simple for loop
res = []
for val in a:
if val not in remove:
res.append(val)
print(res)
Program to print duplicates from a list of
integers in Python
a = [1, 2, 3, 1, 2, 4, 5, 6, 5]
# Initialize an empty set to store seen elements
s = set()
# List to store duplicates
dup = []
for n in a:
if n in s:
dup.append(n)
else:
s.add(n)
print(dup)