Introduction to Arrays in Python
Arrays are one of the most commonly used data structures in programming. They allow us to store multiple values of the same data type in a single variable. In Python, arrays are represented as lists.
Creating an Array
To create an array in Python, you can simply define a list and initialize it with some values. For example:
1# Create an empty list
2numbers = []
3
4# Add elements to the list
5numbers.append(1)
6numbers.append(2)
7numbers.append(3)
8
9print(numbers) # Output: [1, 2, 3]
Accessing Elements
You can access individual elements of an array using their index. The index of the first element is 0, the second element is 1, and so on. For example:
1print(numbers[0]) # Output: 1
2print(numbers[1]) # Output: 2
3print(numbers[2]) # Output: 3
Modifying Elements
You can modify elements of an array by assigning new values to their respective indices. For example:
1numbers[1] = 4
2print(numbers) # Output: [1, 4, 3]
Iterating Over an Array
You can iterate over the elements of an array using a for
loop. For example:
1for num in numbers:
2 print(num)
This will output each element of the array on a separate line.
In the next lesson, we will explore working with objects and learn how to work with properties in Course course one.
xxxxxxxxxx
if __name__ == "__main__":
# Python logic here
# Create an empty list
numbers = []
# Add elements to the list
numbers.append(1)
numbers.append(2)
numbers.append(3)
# Access individual elements
print(numbers[0]) # Output: 1
print(numbers[1]) # Output: 2
print(numbers[2]) # Output: 3
# Modify elements
numbers[1] = 4
print(numbers) # Output: [1, 4, 3]
# Iterate over the list
for num in numbers:
print(num)
print("Print something")