Python - Arrays
append()
method in Python arrays?The append()
method in Python arrays is used to add elements to the end of the array. Here's an example program demonstrating the use of the append()
method:
# Create an array
my_array = [1, 2, 3, 4, 5]
# Display the original array
print("Original Array:", my_array)
# Append a new element to the array
my_array.append(6)
# Display the array after appending
print("Array after Append:", my_array)
Output:
Original Array: [1, 2, 3, 4, 5] Array after Append: [1, 2, 3, 4, 5, 6]
In this example, the append()
method is used to add the element 6
to the end of the array my_array
.
extend()
and append()
methods for arrays.The extend()
and append()
methods in Python arrays are used to add elements, but they differ in their behavior. Let's discuss the difference with examples:
# Using extend() method
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr1.extend(arr2)
print("Using extend():", arr1)
# Using append() method
arr3 = [1, 2, 3]
arr4 = [4, 5, 6]
arr3.append(arr4)
print("Using append():", arr3)
Output:
Using extend(): [1, 2, 3, 4, 5, 6] Using append(): [1, 2, 3, [4, 5, 6]]
The extend()
method adds elements from an iterable (like a list or tuple) to the end of the array, effectively extending it. In contrast, the append()
method adds its argument as a single element to the end of the array. If the argument is an iterable, it is added as a nested list within the array.
To remove an element from a specific index in a Python array, you can use the pop()
method. Here's an example:
# Create an array
my_array = [1, 2, 3, 4, 5]
# Remove element at index 2
removed_element = my_array.pop(2)
print("Original Array:", my_array)
print("Removed Element:", removed_element)
Output:
Original Array: [1, 2, 4, 5] Removed Element: 3
The pop()
method removes and returns the element at the specified index. In the example, the element at index 2 (value 3) is removed from the array, and the modified array is printed along with the removed element.
Array concatenation in Python involves combining two or more arrays into a single array. This can be done using the +
operator or the extend()
method. Here's an example:
# Create two arrays
array1 = [1, 2, 3]
array2 = [4, 5, 6]
# Concatenate arrays using the + operator
concatenated_array1 = array1 + array2
# Concatenate arrays using the extend() method
array1.extend(array2)
concatenated_array2 = array1
print("Using + operator:", concatenated_array1)
print("Using extend() method:", concatenated_array2)
Output:
Using + operator: [1, 2, 3, 4, 5, 6] Using extend() method: [1, 2, 3, 4, 5, 6]
In the example, two arrays (array1
and array2
) are concatenated using both the +
operator and the extend()
method. The resulting concatenated arrays are printed.