Dive Into Arrays in Python PDF
Dive Into Arrays in Python PDF
features and how they can be used to manipulate data efficiently. Whether
you're new to programming or looking to expand your skills, this guide will help
you understand how arrays work and how to use them effectively in your
projects. Let’s get started!
Understanding Arrays: The
Basics
Definition Comparison: Lists vs. Arrays
An array is a collection of elements of the same type stored in Lists are dynamic and flexible, allowing elements of different
contiguous memory locations. They offer efficient storage and data types. Arrays, on the other hand, require all elements to be
access to data. of the same data type.
Indexing in
Arrays:
Accessing
Elements
1 Zero-Based 2 Positive
Indexing Indexing
Array indices start from 0, with Access elements from the
0 representing the first beginning (e.g., my_array[1]
element. refers to the second element).
3 Negative Indexing
Access elements from the end (e.g., my_array[-1] refers to the last
element).
Indexing in
arrays
example
numbers = [10, 20, 30, 40]
# Positive indexing
print(numbers[0]) # Output:
10
# Negative indexing
print(numbers[-1]) # Output:
40
Common Array
Functions
append() len()
Adds an element to the end of Returns the number of elements
the array. in the array.
sort()
Sorts the elements in ascending order.
Examples of
basic built in
functions
numbers = [40, 10, 30]
# Appending an element
numbers.append(20)
print(numbers) # Output: [40, 10, 30,
20]
# Sorting the array
numbers.sort()
print(numbers) # Output: [10, 20, 30,
40]
# Finding the length
print(len(numbers)) # Output: 4
Introducing
Linear Search
Simple Algorithm
1 Linear search checks each element in an array sequentially to
find a target element.
Iterative Process
2 It starts from the beginning and compares each element with
the target, stopping when a match is found.
Efficiency
3 Linear search is simple, but it takes longer as the array gets
bigger.
Linear Search in
Action: Code
Example
numbers = [10, 20,
30, 40]
target
# = 30
Linear search implementation
for i in range(len(numbers)):
if numbers[i] == target:
print("Element found at index" i)
break
else:
print("Element not found")
Key Takeaways: Mastering
Arrays