1 Dimensional Arrays
Introduction to One-Dimensional Arrays
What is an Array?
One-Dimensional Arrays
["cat","dog","mouse","bear"]
Declaring and Initializing One-Dimensional Arrays
my_list = [10, 20, 30, 40, 50] # Creating a list of integers
What is an array?
Looping through arrays
To loop through a Python list (also known as traversing a list/array), you can use various types of loops, such as the for loop or the while loop. Here's how to do it using the for loop:
# Using a for loop to iterate through a list (array)
my_list = [10, 20, 30, 40, 50]
# Method 1: Using range and len
for i in range(len(my_list)):
print(my_list[i])
# Method 2: Using direct iteration
for item in my_list:
print(item)
Searching Arrays
You can search for the index of an item in a list:
# Searching for an element in a Python list and printing its index
# Sample list
my_list = [10, 20, 30, 40, 50]
# Search value
search_value = 30
# Using the index() method
if search_value in my_list:
index = my_list.index(search_value)
print(f"{search_value} found at index {index}.")
else:
print(f"{search_value} not found in the list.")
Adding Items to a List
You can add and remove items from a Python list using various built-in methods. Here's how you can do it:
Append:
Adds an item to the end of the list.
my_list = [10, 20, 30]
my_list.append(40)
print(my_list) # Output: [10, 20, 30, 40]
Insert:
Inserts an item at a specific index.
my_list = [10, 20, 30]
my_list.insert(1, 15)
print(my_list) # Output: [10, 15, 20, 30]
Extend:
Appends elements from another iterable to the end of the list.
my_list = [10, 20, 30]
my_list.extend([40, 50])
print(my_list) # Output: [10, 20, 30, 40, 50]
Removing Items from a List
Remove: Removes the first occurrence of a specific value.
my_list = [10, 20, 30, 20, 40]
my_list.remove(20)
print(my_list) # Output: [10, 30, 20, 40]
Pop: Removes and returns the item at a specific index.
my_list = [10, 20, 30, 40]
removed_item = my_list.pop(1)
print(removed_item) # Output: 20
print(my_list) # Output: [10, 30, 40]
One dimensional arrays
- Introduction to One-Dimensional Arrays
- Looping through arrays
- Searching Arrays
- Adding Items to a List
- Removing Items from a List