Python Lists - Solutions
🔢 Exercise 1: Access by Index
python
# Input: 10 20 30 40 50
arr = list(map(int, input("Enter elements: ").split(" ")))
index = int(input("Enter index: "))
print(arr[index])
🔢 Exercise 2: Count Equal to Last
python
# Input: 5 3 5 7 5 5
arr = list(map(int, input("Enter elements: ").split(" ")))
last = arr[-1]
count = 0
for num in arr:
if num == last:
count += 1
print(count)
🔢 Exercise 3: Elements Greater than Average
python
# Input: 10 20 30 40 50
arr = list(map(int, input("Enter elements: ").split(" ")))
average = sum(arr) / len(arr)
print(f"Average: {average}")
print("Elements greater than average:")
for num in arr:
if num > average:
print(num)
🔢 Exercise 4: Find Maximum and Its Position
python
# Input: 15 42 8 23
arr = list(map(int, input("Enter elements: ").split(" ")))
max_value = arr[0]
max_index = 0
# Loop through list (starting from index 1)
for i in range(1, len(arr)):
if arr[i] > max_value:
max_value = arr[i]
max_index = i
print(f"Maximum value: {max_value}")
print(f"Index: {max_index}")
🔢 Exercise 5: Reverse the List
python
# Input: 1 2 3 4 5
arr = list(map(int, input("Enter elements: ").split(" ")))
# Iterate backwards from last index to 0
for i in range(len(arr) - 1, -1, -1):
print(arr[i], end=" ")
🔢 Exercise 6: Count Occurrences
python
# Input: 3 5 3 7 3 8 3
arr = list(map(int, input("Enter elements: ").split(" ")))
target = int(input("Enter target: "))
count = 0
for num in arr:
if num == target:
count += 1
print(count)
🔢 Exercise 7: Even and Odd Separation
python
# Input: 12 7 8 15 4 9
arr = list(map(int, input("Enter elements: ").split(" ")))
even = []
odd = []
for num in arr:
if num % 2 == 0:
even.append(num)
else:
odd.append(num)
print(f"Even: {even}")
print(f"Odd: {odd}")
🔢 Exercise 8: Remove Duplicates
python
# Input: 5 3 5 7 3 8 5
arr = list(map(int, input("Enter elements: ").split(" ")))
unique = []
for num in arr:
if num not in unique:
unique.append(num)
print(f"Unique: {unique}")
🔢 Exercise 9: Sum of Two Adjacent Elements
python
# Input: 10 20 30 40
arr = list(map(int, input("Enter elements: ").split(" ")))
result = []
for i in range(len(arr) - 1):
sum_adjacent = arr[i] + arr[i+1]
result.append(sum_adjacent)
print(result)
🔢 Exercise 10: Find Second Largest
python
# Input: 45 23 67 12 89
arr = list(map(int, input("Enter elements: ").split(" ")))
arr.sort()
# Second largest is at index len(arr) - 2
second_largest = arr[len(arr) - 2]
print(second_largest)