Python Array Programs
Contents
1 Print All Negative Elements 2
2 Sum of All Elements 2
3 Maximum and Minimum Elements 3
4 Second Largest Element 4
5 Count Even and Odd Elements 4
6 Count Negative Elements 5
7 Copy Array to Another Array 6
8 Insert Element at Position 6
9 Delete Element by Value (First Occurrence) 7
10 Delete Element at Position 8
11 Count Frequency of Each Element 9
12 Print Unique Elements 10
13 Print Only Duplicate Elements 10
14 Count Total Duplicate Elements 11
15 Delete All Duplicate Elements 12
16 Sum of Prime Elements 13
1
1. Print All Negative Elements
Method 1: Manual (Without Built-ins)
1 # Using basic loop
2 arr = [5, -3, 8, -1, 0, -7, 12]
3 print("Negative elements:")
4
5 for i in range(len(arr)):
6 if arr[i] < 0:
7 print(arr[i], end=" ")
8 print()
Method 2: Using Built-in Features
1 # Using list comprehension and filter
2 arr = [5, -3, 8, -1, 0, -7, 12]
3
4 # List comprehension
5 negatives = [x for x in arr if x < 0]
6 print("Negative elements:", negatives)
7
8 # Using filter
9 negatives2 = list(filter(lambda x: x < 0, arr))
10 print("Using filter:", negatives2)
Output
Negative elements:
-3 -1 -7
Negative elements: [-3, -1, -7]
Using filter: [-3, -1, -7]
2. Sum of All Elements
Method 1: Manual
1 arr = [1, 2, 3, 4, 5]
2 total = 0
3
4 for i in range(len(arr)):
5 total += arr[i]
6
7 print("Sum (manual):", total)
Method 2: Using Built-in
1 arr = [1, 2, 3, 4, 5]
2
3 # Using sum()
4 total = sum(arr)
2
5 print("Sum (built-in):", total)
6
7 # Using reduce
8 from functools import reduce
9 total2 = reduce(lambda a, b: a + b, arr)
10 print("Sum (reduce):", total2)
Output
Sum (manual): 15
Sum (built-in): 15
Sum (reduce): 15
3. Maximum and Minimum Elements
Method 1: Manual
1 arr = [4, 7, 1, 9, 3]
2
3 # Initialize with first element
4 max_val = arr[0]
5 min_val = arr[0]
6
7 for i in range(1, len(arr)):
8 if arr[i] > max_val:
9 max_val = arr[i]
10 if arr[i] < min_val:
11 min_val = arr[i]
12
13 print("Maximum (manual):", max_val)
14 print("Minimum (manual):", min_val)
Method 2: Using Built-in
1 arr = [4, 7, 1, 9, 3]
2
3 max_val = max(arr)
4 min_val = min(arr)
5
6 print("Maximum (built-in):", max_val)
7 print("Minimum (built-in):", min_val)
Output
Maximum (manual): 9
Minimum (manual): 1
Maximum (built-in): 9
Minimum (built-in): 1
3
4. Second Largest Element
Method 1: Manual
1 arr = [10, 20, 5, 8, 20, 15]
2
3 # Find first and second largest
4 first = second = float(’-inf’)
5
6 for i in range(len(arr)):
7 if arr[i] > first:
8 second = first
9 first = arr[i]
10 elif arr[i] > second and arr[i] != first:
11 second = arr[i]
12
13 if second == float(’-inf’):
14 print("No second largest element")
15 else:
16 print("Second largest (manual):", second)
Method 2: Using Built-in
1 arr = [10, 20, 5, 8, 20, 15]
2
3 # Remove duplicates and sort
4 unique_sorted = sorted(set(arr), reverse=True)
5
6 if len(unique_sorted) >= 2:
7 print("Second largest (built-in):", unique_sorted[1])
8 else:
9 print("No second largest element")
Output
Second largest (manual): 15
Second largest (built-in): 15
5. Count Even and Odd Elements
Method 1: Manual
1 arr = [1, 2, 3, 4, 5, 6, 7, 8]
2 even_count = 0
3 odd_count = 0
4
5 for i in range(len(arr)):
6 if arr[i] % 2 == 0:
7 even_count += 1
8 else:
9 odd_count += 1
10
11 print("Even count (manual):", even_count)
12 print("Odd count (manual):", odd_count)
4
Method 2: Using Built-in
1 arr = [1, 2, 3, 4, 5, 6, 7, 8]
2
3 even_count = sum(1 for x in arr if x % 2 == 0)
4 odd_count = sum(1 for x in arr if x % 2 != 0)
5
6 print("Even count (built-in):", even_count)
7 print("Odd count (built-in):", odd_count)
8
9 # Alternative using filter
10 even_count2 = len(list(filter(lambda x: x % 2 == 0, arr)))
11 odd_count2 = len(list(filter(lambda x: x % 2 != 0, arr)))
Output
Even count (manual): 4
Odd count (manual): 4
Even count (built-in): 4
Odd count (built-in): 4
6. Count Negative Elements
Method 1: Manual
1 arr = [-1, 5, -4, 10, -8, 3]
2 count = 0
3
4 for i in range(len(arr)):
5 if arr[i] < 0:
6 count += 1
7
8 print("Negative count (manual):", count)
Method 2: Using Built-in
1 arr = [-1, 5, -4, 10, -8, 3]
2
3 count = sum(1 for x in arr if x < 0)
4 print("Negative count (built-in):", count)
5
6 # Alternative
7 count2 = len([x for x in arr if x < 0])
8 print("Alternative count:", count2)
Output
Negative count (manual): 3
Negative count (built-in): 3
Alternative count: 3
5
7. Copy Array to Another Array
Method 1: Manual
1 arr = [1, 2, 3, 4, 5]
2 copy_arr = []
3
4 for i in range(len(arr)):
5 copy_arr.append(arr[i])
6
7 print("Original:", arr)
8 print("Copy (manual):", copy_arr)
9 print("Are they same object?", arr is copy_arr)
Method 2: Using Built-in
1 arr = [1, 2, 3, 4, 5]
2
3 # Method 1: Using copy() method
4 copy1 = [Link]()
5
6 # Method 2: Using list() constructor
7 copy2 = list(arr)
8
9 # Method 3: Using slicing
10 copy3 = arr[:]
11
12 # Method 4: Using copy module
13 import copy
14 copy4 = [Link](arr)
15
16 print("Original:", arr)
17 print("Copy1:", copy1)
18 print("Copy2:", copy2)
19 print("Copy3:", copy3)
Output
Original: [1, 2, 3, 4, 5]
Copy (manual): [1, 2, 3, 4, 5]
Are they same object? False
8. Insert Element at Position
Method 1: Manual
1 arr = [10, 20, 40, 50]
2 pos = 2
3 value = 30
4 new_arr = []
5
6 for i in range(len(arr) + 1):
7 if i < pos:
6
8 new_arr.append(arr[i])
9 elif i == pos:
10 new_arr.append(value)
11 else:
12 new_arr.append(arr[i - 1])
13
14 print("After insertion (manual):", new_arr)
Method 2: Using Built-in
1 arr = [10, 20, 40, 50]
2 pos = 2
3 value = 30
4
5 # Method 1: Using insert()
6 [Link](pos, value)
7 print("After insertion (built-in):", arr)
8
9 # Method 2: Using slicing
10 arr2 = [10, 20, 40, 50]
11 arr2 = arr2[:pos] + [value] + arr2[pos:]
12 print("Using slicing:", arr2)
Output
After insertion (manual): [10, 20, 30, 40, 50]
After insertion (built-in): [10, 20, 30, 40, 50]
Using slicing: [10, 20, 30, 40, 50]
9. Delete Element by Value (First Occurrence)
Method 1: Manual
1 arr = [10, 20, 30, 40, 30]
2 value = 30
3 new_arr = []
4 found = False
5
6 for i in range(len(arr)):
7 if arr[i] == value and not found:
8 found = True
9 continue # Skip this element
10 new_arr.append(arr[i])
11
12 print("After deletion (manual):", new_arr)
Method 2: Using Built-in
1 arr = [10, 20, 30, 40, 30]
2 value = 30
3
4 # Using remove() - removes first occurrence
5 try:
7
6 [Link](value)
7 print("After deletion (built-in):", arr)
8 except ValueError:
9 print("Value not found")
10
11 # Alternative: Using list comprehension (removes all)
12 arr2 = [10, 20, 30, 40, 30]
13 arr2 = [x for x in arr2 if x != value]
14 print("Removes all occurrences:", arr2)
Output
After deletion (manual): [10, 20, 40, 30]
After deletion (built-in): [10, 20, 40, 30]
Removes all occurrences: [10, 20, 40]
10. Delete Element at Position
Method 1: Manual
1 arr = [10, 20, 30, 40, 50]
2 pos = 2
3 new_arr = []
4
5 for i in range(len(arr)):
6 if i != pos:
7 new_arr.append(arr[i])
8
9 print("After deletion (manual):", new_arr)
Method 2: Using Built-in
1 arr = [10, 20, 30, 40, 50]
2 pos = 2
3
4 # Method 1: Using pop()
5 deleted = [Link](pos)
6 print("Deleted element:", deleted)
7 print("After deletion (built-in):", arr)
8
9 # Method 2: Using del
10 arr2 = [10, 20, 30, 40, 50]
11 del arr2[pos]
12 print("Using del:", arr2)
13
14 # Method 3: Using slicing
15 arr3 = [10, 20, 30, 40, 50]
16 arr3 = arr3[:pos] + arr3[pos+1:]
17 print("Using slicing:", arr3)
Output
After deletion (manual): [10, 20, 40, 50]
8
Deleted element: 30
After deletion (built-in): [10, 20, 40, 50]
Using del: [10, 20, 40, 50]
Using slicing: [10, 20, 40, 50]
11. Count Frequency of Each Element
Method 1: Manual
1 arr = [1, 2, 1, 3, 2, 1, 4, 3]
2 freq = {}
3
4 for i in range(len(arr)):
5 count = 0
6 # Count occurrences of arr[i]
7 for j in range(len(arr)):
8 if arr[j] == arr[i]:
9 count += 1
10 freq[arr[i]] = count
11
12 print("Frequency (manual):")
13 for key, value in [Link]():
14 print(f"{key}: {value}")
Method 2: Using Built-in
1 arr = [1, 2, 1, 3, 2, 1, 4, 3]
2
3 # Method 1: Using count()
4 unique = set(arr)
5 freq = {x: [Link](x) for x in unique}
6 print("Frequency (built-in):", freq)
7
8 # Method 2: Using Counter
9 from collections import Counter
10 freq2 = Counter(arr)
11 print("Using Counter:", dict(freq2))
12
13 # Method 3: Manual with dict
14 freq3 = {}
15 for x in arr:
16 freq3[x] = [Link](x, 0) + 1
17 print("Using get():", freq3)
Output
Frequency (manual):
1: 3
2: 2
3: 2
4: 1
Frequency (built-in): {1: 3, 2: 2, 3: 2, 4: 1}
Using Counter: {1: 3, 2: 2, 3: 2, 4: 1}
9
Using get(): {1: 3, 2: 2, 3: 2, 4: 1}
12. Print Unique Elements
Method 1: Manual
1 arr = [1, 2, 2, 3, 4, 4, 5]
2 printed = []
3
4 print("Unique elements (manual):")
5 for i in range(len(arr)):
6 count = 0
7 for j in range(len(arr)):
8 if arr[j] == arr[i]:
9 count += 1
10
11 # Print only if appears once and not printed before
12 if count == 1 and arr[i] not in printed:
13 print(arr[i], end=" ")
14 [Link](arr[i])
15 print()
Method 2: Using Built-in
1 arr = [1, 2, 2, 3, 4, 4, 5]
2
3 # Method 1: Using count()
4 unique = [x for x in arr if [Link](x) == 1]
5 print("Unique elements (built-in):", unique)
6
7 # Method 2: Using Counter
8 from collections import Counter
9 freq = Counter(arr)
10 unique2 = [x for x, count in [Link]() if count == 1]
11 print("Using Counter:", unique2)
Output
Unique elements (manual): 1 3 5
Unique elements (built-in): [1, 3, 5]
Using Counter: [1, 3, 5]
13. Print Only Duplicate Elements
Method 1: Manual
1 arr = [1, 2, 2, 3, 3, 4, 5, 5]
2 printed = []
3
4 print("Duplicate elements (manual):")
5 for i in range(len(arr)):
6 count = 0
10
7 for j in range(len(arr)):
8 if arr[j] == arr[i]:
9 count += 1
10
11 if count > 1 and arr[i] not in printed:
12 print(arr[i], end=" ")
13 [Link](arr[i])
14 print()
Method 2: Using Built-in
1 arr = [1, 2, 2, 3, 3, 4, 5, 5]
2
3 # Method 1: Using count() with set
4 duplicates = list(set([x for x in arr if [Link](x) > 1]))
5 print("Duplicate elements (built-in):", duplicates)
6
7 # Method 2: Using Counter
8 from collections import Counter
9 freq = Counter(arr)
10 duplicates2 = [x for x, count in [Link]() if count > 1]
11 print("Using Counter:", duplicates2)
Output
Duplicate elements (manual): 2 3 5
Duplicate elements (built-in): [2, 3, 5]
Using Counter: [2, 3, 5]
14. Count Total Duplicate Elements
Method 1: Manual
1 arr = [1, 2, 2, 3, 3, 3, 4]
2 counted = []
3 dup_count = 0
4
5 for i in range(len(arr)):
6 if arr[i] in counted:
7 continue
8
9 count = 0
10 for j in range(len(arr)):
11 if arr[j] == arr[i]:
12 count += 1
13
14 if count > 1:
15 dup_count += 1
16 [Link](arr[i])
17
18 print("Total duplicate elements (manual):", dup_count)
11
Method 2: Using Built-in
1 arr = [1, 2, 2, 3, 3, 3, 4]
2
3 # Count unique elements that appear more than once
4 from collections import Counter
5 freq = Counter(arr)
6 dup_count = sum(1 for count in [Link]() if count > 1)
7 print("Total duplicate elements (built-in):", dup_count)
8
9 # Alternative
10 dup_count2 = len([x for x in set(arr) if [Link](x) > 1])
11 print("Alternative count:", dup_count2)
Output
Total duplicate elements (manual): 2
Total duplicate elements (built-in): 2
Alternative count: 2
15. Delete All Duplicate Elements
Method 1: Manual
1 arr = [1, 2, 2, 3, 3, 3, 4, 5]
2 new_arr = []
3
4 for i in range(len(arr)):
5 found = False
6 for j in range(len(new_arr)):
7 if new_arr[j] == arr[i]:
8 found = True
9 break
10
11 if not found:
12 new_arr.append(arr[i])
13
14 print("After removing duplicates (manual):", new_arr)
Method 2: Using Built-in
1 arr = [1, 2, 2, 3, 3, 3, 4, 5]
2
3 # Method 1: Using set (doesn’t preserve order)
4 unique1 = list(set(arr))
5 print("Using set:", unique1)
6
7 # Method 2: Using dict (preserves order in Python 3.7+)
8 unique2 = list([Link](arr))
9 print("Using [Link]:", unique2)
10
11 # Method 3: List comprehension with tracking
12 seen = []
13 unique3 = [x for x in arr if not (x in seen or [Link](x))]
12
14 print("Using list comprehension:", unique3)
Output
After removing duplicates (manual): [1, 2, 3, 4, 5]
Using set: [1, 2, 3, 4, 5]
Using [Link]: [1, 2, 3, 4, 5]
Using list comprehension: [1, 2, 3, 4, 5]
16. Sum of Prime Elements
Method 1: Manual
1 def is_prime_manual(n):
2 if n < 2:
3 return False
4 if n == 2:
5 return True
6 if n % 2 == 0:
7 return False
8
9 # Check odd divisors up to sqrt(n)
10 i = 3
11 while i * i <= n:
12 if n % i == 0:
13 return False
14 i += 2
15 return True
16
17 arr = [2, 3, 4, 5, 9, 11, 15, 17]
18 prime_sum = 0
19
20 for i in range(len(arr)):
21 if is_prime_manual(arr[i]):
22 prime_sum += arr[i]
23
24 print("Sum of primes (manual):", prime_sum)
Method 2: Using Built-in
1 def is_prime(n):
2 if n < 2:
3 return False
4 return all(n % i != 0 for i in range(2, int(n**0.5) + 1))
5
6 arr = [2, 3, 4, 5, 9, 11, 15, 17]
7
8 # Method 1: Using sum with filter
9 prime_sum = sum(filter(is_prime, arr))
10 print("Sum of primes (built-in):", prime_sum)
11
12 # Method 2: Using sum with comprehension
13 prime_sum2 = sum(x for x in arr if is_prime(x))
14 print("Using comprehension:", prime_sum2)
13
15
16 # Method 3: Using sympy library
17 try:
18 from sympy import isprime
19 prime_sum3 = sum(x for x in arr if isprime(x))
20 print("Using sympy:", prime_sum3)
21 except ImportError:
22 print("sympy not available")
Output
Sum of primes (manual): 38
Sum of primes (built-in): 38
Using comprehension: 38
Summary
This document covers 16 fundamental array operations in Python with both manual imple-
mentations (using basic loops) and built-in/Pythonic approaches.
Key Takeaways:
• Manual methods help understand algorithms
• Built-in methods are more concise and often faster
• Python offers multiple ways to solve problems
• Choose the approach based on requirements (readability, performance, constraints)
14