Sitemap

Array in C++ ,Python(list)

12 min readSep 25, 2025

--

Array is collection of similar items stored in contiguous memory collections

  • Collection: Holds multiple values under one name ⇒array = [10, 20, 30, 40]
  • Index-based: Each element is accessed by its index (position) ⇒ Index → Used by the computer (starts at 0).Position → Used by humans (starts at 1)
  • `arr[0]` → **index = 0**, **position = 1 (first element)**
  • `arr[2]` → **index = 2**, **position = 3 (third element)**
  • Fixed Size: Most arrays have a fixed size once created.
  • Efficient Access: Accessing an element by index takes constant time O(1).

TYPES IN ARRAY

Arrays are usually classified in two ways:

1. Based on Dimension

  • One-dimensional array (1D) → A simple list of elements.

array = [10, 20, 30] # 1D array

  • Two-dimensional array (2D) → An array of arrays (like a table/matrix).

matrix = [[1, 2, 3], [4, 5, 6]] # 2D array

  • Multi-dimensional array (3D, 4D, …) → Used for complex data like images.
  • Example: a 3D array can represent multiple 2D matrices.

2. Based on Data Type (depends on language)

  • Integer array → [1, 2, 3]
  • Float array → [1.1, 2.2, 3.3]
  • Character array (string in many languages) → ['a', 'b', 'c']
  • Boolean array → [True, False, True]
  • In Python, a list can hold mixed types (e.g., [1, "hello", 3.14]), but in C, C++, or Java, arrays usually store elements of only one type.
  • Arrays in C, C++, Java → Fixed size (once declared, they cannot grow or shrink).
  • Lists in Python → Dynamic size (you can append or remove elements at any time).
  • Low-level languages (C, C++, Java) → arrays = same datatype.
  • High-level (Python, JavaScript) → arrays (lists) can hold mixed datatypes, but that may not be efficient.

Basic Operations on Arrays

  1. Traversal
  2. Insertion (first, last, nth, middle)
  3. Deletion (first, last, nth, middle)
  4. Searching (linear & binary)
  5. Updating (replace value at given index)

1. Traversal

#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5;
cout << "Array elements: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
}

2. Insertion

a) Insert at the End

#include <iostream>
using namespace std;
int main() {
int arr[10] = {1, 2, 3, 4, 5};
int n = 5, element = 99;
arr[n] = element;
n++;
cout << "After inserting at end: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
}

b) Insert at the Beginning

#include <iostream>
using namespace std;
int main() {
int arr[10] = {10, 20, 30, 40, 50};
int n = 5, element = 5;
for (int i = n; i > 0; i--) arr[i] = arr[i - 1];
arr[0] = element;
n++;
cout << "After inserting at beginning: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
}

c) Insert at nth Position

#include <iostream>
using namespace std;
int main() {
int arr[10] = {11, 22, 33, 44, 55};
int n = 5, element = 99, pos = 2; // insert at index 2
for (int i = n; i > pos; i--) arr[i] = arr[i - 1];
arr[pos] = element;
n++;
cout << "After inserting at index " << pos << ": ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
}

d) Insert in the Middle

#include <iostream>
using namespace std;
int main() {
int arr[10] = {2, 4, 6, 8, 10};
int n = 5, element = 99, pos = n / 2;
for (int i = n; i > pos; i--) arr[i] = arr[i - 1];
arr[pos] = element;
n++;
cout << "After inserting in middle: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
}

3. Deletion

a) Delete from End

#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5;
n--; // remove last element cout << "After deleting from end: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
}

b) Delete from Beginning

#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5;
for (int i = 0; i < n - 1; i++) arr[i] = arr[i + 1];
n--;
cout << "After deleting from beginning: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
}

c) Delete at nth Position

#include <iostream>
using namespace std;
int main() {
int arr[] = {11, 22, 33, 44, 55};
int n = 5, pos = 2; // delete index 2
for (int i = pos; i < n - 1; i++) arr[i] = arr[i + 1];
n--;
cout << "After deleting at index " << pos << ": ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
}

d) Delete from Middle

#include <iostream>
using namespace std;
int main() {
int arr[] = {2, 4, 6, 8, 10};
int n = 5, pos = n / 2;
for (int i = pos; i < n - 1; i++) arr[i] = arr[i + 1];
n--;
cout << "After deleting from middle: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
}

4. Searching

a) Linear Search

#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 25, 30, 45, 50};
int n = 5, key = 30, found = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
found = i;
break;
}
}
if (found != -1) cout << "Element found at index " << found;
else cout << "Element not found";
}

b) Binary Search (requires sorted array)

#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = 5, key = 40;
int low = 0, high = n - 1, mid, found = -1;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key) {
found = mid;
break;
} else if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
if (found != -1) cout << "Element found at index " << found;
else cout << "Element not found";
}

5. Updating

#include <iostream>
using namespace std;
int main() {
int arr[] = {5, 10, 15, 20, 25};
int n = 5, pos = 2, newValue = 99; // update index 2
arr[pos] = newValue; cout << "After updating at index " << pos << ": ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
}

Operation Best Case Worst Case Space Traversal O(n) O(n) O(1) Insert (end) O(1) O(1) O(1) Insert (begin) O(n) O(n) O(1) Insert (middle) O(n) O(n) O(1) Delete (end) O(1) O(1) O(1) Delete (begin) O(n) O(n) O(1) Delete (middle) O(n) O(n) O(1) Linear Search O(1) O(n) O(1) Binary Search O(1) O(log n) O(1) Update O(1) O(1) O(1)

BASIC OPERATIONS IN PYTHON LIST OPERATIONS(DYNAMIC ARRAY)

1️⃣ Traversal

# Traversal: Visit each element
arr = [10, 20, 30, 40, 50]
print("Traversal of array:")
for i in range(len(arr)):
print(f"Index {i}: {arr[i]}")

Insertion

arr = [10, 20, 30, 40, 50]
# Insert at first position
arr.insert(0, 5)
print("After inserting at first position:", arr)
# Insert at last position
arr.append(60)
print("After inserting at last position:", arr)
# Insert at nth position (index 3)
arr.insert(3, 25)
print("After inserting at index 3 (middle):", arr)
# Insert at middle position (roughly)
middle_index = len(arr) // 2
arr.insert(middle_index, 35)
print("After inserting at middle position:", arr)

Deletion

arr = [5, 10, 20, 25, 30, 35, 40, 50, 60]
# Delete first element
arr.pop(0)
print("After deleting first element:", arr)
# Delete last element
arr.pop()
print("After deleting last element:", arr)
# Delete nth element (index 2)
arr.pop(2)
print("After deleting element at index 2:", arr)
# Delete middle element (roughly)
middle_index = len(arr) // 2
arr.pop(middle_index)
print("After deleting middle element:", arr)

Searching

arr = [10, 20, 30, 40, 50]
# Linear search
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
print("Linear Search for 30:", linear_search(arr, 30)) # index 2# Binary search (array must be sorted)
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print("Binary Search for 40:", binary_search(arr, 40)) # index 3

Updating

arr = [10, 20, 30, 40, 50]
# Update element at index 2
arr[2] = 35
print("After updating index 2 to 35:", arr)
# Update first element
arr[0] = 5
print("After updating first element:", arr)
# Update last element
arr[-1] = 60
print("After updating last element:", arr)

Arrays in C++ and Python: Operations and Complexities

Arrays are fundamental data structures used to store multiple elements in contiguous memory locations. While the concept is similar across languages, there are some key differences between C++ arrays and Python lists. Understanding these differences is crucial for analyzing performance and writing efficient code.

1. Nature of Arrays in C++ vs Python

  • C++ Arrays:
  • In C++, arrays are fixed-size and contiguous in memory. You must define their size when creating them (e.g., int arr[10];). Because the size is fixed, insertion or deletion at arbitrary positions requires shifting elements manually. Accessing elements by index is extremely fast (O(1)), and the memory layout is straightforward, making operations highly efficient.
  • Python Lists:
  • Python lists behave like dynamic arrays. They can grow or shrink automatically as elements are added or removed. Internally, Python lists maintain a contiguous block of memory but may occasionally resize (allocate a bigger block and copy elements) when the capacity is exceeded. This resizing makes some operations like append() amortized O(1) rather than strictly O(1).

2. Common Array Operations

Arrays support several basic operations, such as traversal, insertion, deletion, searching, updating, and sometimes sorting/merging. Let’s analyze them:

a) Traversal

  • Definition: Accessing each element one by one.
  • C++ & Python Complexity: O(n) time, O(1) space.
  • Traversal complexity is identical because you must examine every element.

b) Access by Index

  • Definition: Accessing or updating an element using its index.
  • C++ & Python Complexity: O(1) time, O(1) space.
  • Both allow direct access due to contiguous memory.

c) Insertion

  • At the End:
  • C++: O(1) if space is available; otherwise, new memory allocation is needed (rare).
  • Python: Amortized O(1) because Python may need to resize occasionally.
  • At Beginning or Middle:
  • Both languages require shifting elements to make space.
  • Complexity: O(n) in worst case (e.g., inserting at index 0).

d) Deletion

  • At the End:
  • O(1) in both C++ and Python.
  • At Beginning or Middle:
  • Requires shifting elements to fill the gap.
  • Complexity: O(n) in worst case.

e) Searching

  • Linear Search: Check each element sequentially.
  • Complexity: O(n) time, O(1) space.
  • Binary Search (sorted arrays/lists):
  • Complexity: O(log n) time, O(1) space.

f) Updating

  • Definition: Replacing an element at a given index.
  • C++ & Python Complexity: O(1) time, O(1) space.

3. Key Differences and Notes

  1. Fixed-size vs Dynamic :C++ arrays are fixed in size; Python lists are dynamic. This makes Python more flexible but slightly slower in memory-intensive scenarios.
  2. Insertion and Append :In Python, append() is amortized O(1) due to occasional resizing. In C++ fixed arrays, appending beyond allocated size is impossible; std::vector is needed to mimic dynamic behavior.
  3. Memory Efficiency :C++ arrays are more memory-efficient because elements are stored contiguously with no extra overhead. Python lists store pointers to objects, which uses slightly more memory.
  4. Practical Performance :For large datasets, C++ arrays or vectors are generally faster and more predictable. Python lists provide ease of use and flexibility but with minor overhead.

Conclusion:

Get Athulya Maya’s stories in your inbox

Join Medium for free to get updates from this writer.

C++ arrays: faster, fixed size, more memory-efficient, requires manual handling for dynamic operations.

Python lists: flexible, dynamic, easy to use, slightly more memory overhead, some operations are amortized instead of strict O(1).

Term Starts From Who uses it? Index 0 Computer / Programming Position 1 Human / Conceptual

  • Index → position-1
  • Position → index+1

When Solving Array Problems -index , position

python

Always solve based on index in programming because arrays are 0-indexed.

  • Position is only used for explanation or understanding.

Problem: “Insert 99 at the 3rd position of [10, 20, 30, 40]”

  • Step 1: Convert position → index
  • Position 3 → Index = 3 - 1 = 2
  • Step 2: Insert at index 2
arr = [10, 20, 30, 40]
arr.insert(2, 99)
print(arr) # [10, 20, 99, 30, 40]
#include <iostream>
using namespace std;
int main() {
int arr[10] = {10, 20, 30, 40}; // Original array
int n = 4; // Current number of elements
int pos = 3; // Position where we want to insert
int val = 99; // Value to insert
int index = pos - 1; // Convert position to index // Shift elements right
for(int i = n; i > index; i--) {
arr[i] = arr[i-1];
}
arr[index] = val; // Insert value
n++; // Increase element count
cout << "Array after insertion: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Array after insertion: 10 20 99 30 40

C++ Arrays

  1. Fixed size → You must declare a size large enough to hold new elements.
  • int arr[10]; // can hold 10 elements
  1. Shifting required → For insertion or deletion at middle/first position.
  2. Index always used in code → Position is only for problem explanation.

SHIFTING IN C++ DURING OPERATIONS AND MEMORY HANDLING

Insertion

  • Suppose you want to insert a new element at some index i.
  • You need to make space for it.
  • How shifting works:
  1. Start from the last element of the array.
  2. Move each element one step to the right, going backward toward index i.
  3. Stop when you reach index i.
  • Then, place the new element at index i.

Example: Insert 99 at index 2 in [10, 20, 30, 40]

Before shift: 10 20 30 40
Step 1: move last (40) to index 4 → 10 20 30 40 40
Step 2: move 30 to index 3 → 10 20 30 30 40
Insert 99 at index 2 → 10 20 99 30 40

✅ So yes: last element moves first, then previous ones, until space is ready.

During insertion:

  1. Shifting always starts from the last element to avoid overwriting data.
Original:      10  20  30  40
Shift step 1: 10 20 30 40 ← 40 moves to index 4
Shift step 2: 10 20 30 30 ← 30 moves to index 3
  1. In C++, you must ensure array has enough allocated memory to hold new element.
  2. In Python lists, shifting happens automatically when you do list.insert(index, value).

Memory Handling During Insertion

C++ Fixed-size arrays:

  • Memory is pre-allocated at compile/runtime.
  • If there is space (physical size > logical size), you can just shift elements and insert.
  • If the array is full, you cannot insert; you must:
  1. Declare a bigger array and copy old elements.
  2. Use dynamic memory with new.
  3. Use std::vector (recommended).

Python Lists:

  • Memory is dynamic, handled automatically.
  • During list.insert(index, value), Python:
  1. Shifts elements right automatically.
  2. Allocates more memory if needed (behind the scenes).

Deletion

  • Suppose you want to delete element at index i.

How shifting works:

  1. Start from the element immediately after index i.
  2. Move each element one step to the left.
  3. Stop at the last element.
  4. Then reduce logical size by 1.

Example: Delete element at index 1 in [10, 20, 99, 30, 40]

Before shift: 10 20 99 30 40
Step 1: move 99 (index 2) to index 1 → 10 99 99 30 40
Step 2: move 30 (index 3) to index 2 → 10 99 30 30 40
Step 3: move 40 (index 4) to index 3 → 10 99 30 40 40
Logical size decreases → 10 99 30 40

✅ So yes: element next to the deleted element moves first, then the following ones.

During deletion:

  1. You remove the element at a specific index.
  2. All elements after that index shift left to fill the empty space.
  3. In C++, memory is still allocated (fixed size), but the logical size decreases.
  4. In Python, memory may be adjusted automatically if needed (dynamic array).

Memory Handling During Deletion

C++ Arrays

  • Memory is fixed at compile/runtime.
  • After deletion, the physical memory is not freed.
  • You just decrease the logical size (n--) and ignore the “extra” slot.
int arr[10] = {10,20,99,30,40};
int n = 5; // logical size
int index = 1; // delete element at index 1
for(int i = index; i < n-1; i++)
arr[i] = arr[i+1]; // shift left
n--; // logical size decreases
  • The memory at arr[4] is still allocated, but considered unused.

Python Lists

  • Memory is dynamic, handled by Python automatically.
  • When you do arr.pop(index):
  1. Python shifts elements left automatically.
  2. Removes reference to deleted element → memory can be freed by garbage collector.
arr = [10, 20, 99, 30, 40]
arr.pop(1) # removes 20
print(arr) # [10, 99, 30, 40]

Key Points on Shifting

Operation Start shifting from Direction Insertion Last element Right Deletion Element after deleted Left Operation Shifting Direction Complexity Deletion at start Left O(n) Deletion at middle Left O(n) Deletion at end None O(1)

Rules During Insertion and Deletion

  • During insertion, memory allocation:
  • If the array is full (logical size = physical size), you cannot just increase its size.
  • You need to use one of these methods:
  1. Declare a bigger array and copy old elements.
  2. Use dynamic memory with new.
  3. Use std::vector (recommended for easy insertions)

Summary

  1. Shifting left is done to fill the gap after deletion.
  2. C++ fixed arrays: memory not freed, just reduce logical size.
  3. Python lists: memory handled automatically, removed element memory is freed by garbage collector.
  4. Index always used in code, position is just conceptual.

--

--