Programming & Development / April 19, 2025

Arrays and Strings in Python: Essential Operations and Examples

arrays strings python data structures string manipulation array operations traversal insertion deletion searching sorting coding interview

Arrays and strings are fundamental data structures in Python. Mastering how to work with them efficiently is essential for day-to-day programming and technical interviews.

Let’s explore the key operations for both arrays and strings in Python, along with simple code examples.

📦 Arrays in Python

In Python, arrays are often represented using lists, which are dynamic and support various operations.

🔁 Traversal

python

arr = [1, 2, 3, 4, 5]
for num in arr:
    print(num)

➕ Insertion

python

arr.append(6)         # Add to end
arr.insert(2, 10)     # Insert 10 at index 2

➖ Deletion

python

arr.remove(3)         # Remove first occurrence of 3
del arr[1]            # Delete element at index 1
arr.pop()             # Remove last element

🔍 Searching

python

if 4 in arr:
    print("Found")

🧹 Sorting

python

arr.sort()            # In-place sort
sorted_arr = sorted(arr)  # Returns a new sorted list

🧵 Strings in Python

Strings are immutable sequences of characters in Python. Most operations return new strings.

🔁 Traversal

python

s = "hello"
for char in s:
    print(char)

➕ Insertion (via concatenation)

python

s = "he"
s += "llo"            # s becomes "hello"

➖ Deletion (via slicing)

python

s = "hello"
s = s[:2] + s[3:]     # Remove character at index 2 → "helo"

🔍 Searching

python

"e" in s              # True
s.find("l")           # Returns index of first 'l'

🧹 Sorting (convert to list first)

python

sorted_s = ''.join(sorted(s))  # e.g., "hello" → "ehllo"

🧪 Example: Remove Duplicates from an Array

python

nums = [1, 2, 2, 3, 4, 4]
unique = list(set(nums))
print(unique)  # Output: [1, 2, 3, 4] (order not guaranteed)

🧪 Example: Reverse a String

python

s = "python"
reversed_s = s[::-1]
print(reversed_s)  # Output: "nohtyp"

📝 Final Thoughts

Arrays and strings are everywhere in coding. Understanding their basic operations in Python—like traversal, insertion, and searching—lays the groundwork for solving more complex problems.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex