Python Array

In Python, arrays are usually represented using lists, which are dynamic arrays that can hold elements of different data types. However, if you specifically need arrays with fixed sizes and homogeneous elements, you can use the array module in Python. Let's go through the basic operations with Python lists, which can be used to understand the concept of arrays.

Python Lists (Array-like):

1. Creating a List (Array):
You can create a list by enclosing elements in square brackets [].

        
my_list = [1, 2, 3, 4, 5];
        
    

2. Accessing List Items (Array Elements):
You can access elements in a list using indexing. Indexing starts at 0.

        
first_element = my_list[0];  # Access the first element (1)
        
    

3. Adding Items to a List (Array):
You can add items to a list using the append method.

        
my_list.append(6);  # Adds 6 to the end of the list
        
    

4. Removing Items from a List (Array):
You can remove items from a list using the remove method or the pop method.

        
my_list.remove(3);  # Removes the element with value 3
popped_element = my_list.pop(1);  # Removes and returns the element at index 1
        
    

5. Looping Through a List (Array):
You can iterate over the elements of a list using a for loop.

        
for item in my_list:
    print(item);
        
    

6. Copying a List (Array):
You can create a copy of a list using the copy method or using the list() constructor.

        
copy_of_list = my_list.copy();
        
    

7. Reversing a List (Array):
You can reverse the order of elements in a list using the reverse method.

        
my_list.reverse();
        
    

8. Sorting a List (Array):
You can sort the elements of a list using the sort method.

        
my_list.sort();
        
    

9. Joining Lists (Array Concatenation):
You can join (concatenate) two lists using the + operator.

        
new_list = my_list + [7, 8, 9];
        
    

10. List Methods:
There are various methods available for lists. You can explore them using the help(list) command in the Python interpreter.

        
help(list);
        
    

These basic operations cover most of the essential aspects of working with arrays or array-like structures in Python using lists.

Next Topic