Page Content

Tutorials

What are the Arrays in Python With Code Example

Arrays in Python

Arrays in Python
Arrays in Python

In Python, arrays also known as lists or NumPy arrays in Python are essential data structures for storing data collections. A straightforward data collection that can store multiple values at once is Python’s built-in list type. The ndarray object for multi-dimensional arrays in Python of homogenous data types is provided by the NumPy library, which is widely used in data science and is made for effective numerical computations.

This explanation focusses on array exercises, array methods, and arrays in Python item access:

Accessing Array Items

One of the fundamental functions of an array or list is the ability to access individual objects or groups of items. Indexing and slicing are the main methods used for this.

Indexing:A list or array contains a numerical index for each of its elements. Indexing in Python begins at 0. Square brackets [offset] can be used to retrieve an object by its offset (index). For example, index 0 is used to obtain the first item. Negative indexes, in which -1 is the last item, can likewise be used to access items from the end.

Slicing: By defining a range of indices, a slice allows you to retrieve numerous items from a list or array. The syntax [start : end] is used for this. A new sequence made by slicing includes components from the start index all the way up to the end index, but excludes the finish index.

Multi-dimensional indexing is used for multi-dimensional arrays, such as nested lists (lists of lists) or NumPy ndarray objects. List Name[row Index] [column Index] is a way to access an element in a two-dimensional list.

Code Example for Accessing Items:

# Using a Python list
my_list = [21, 32, 38-40]
# Accessing elements by positive index
# "print(First element:, my_list)  " 
# "print(Third element:, my_list[41])  " 
# Accessing elements by negative index
print("Last element:", my_list[-1])
# Accessing elements using slicing
print("Elements from index 1 to 3 (exclusive):", my_list[1:4])
print("Elements from the beginning up to index 3 (exclusive):", my_list[:3])
print("Elements from index 2 to the end:", my_list[2:])
# Using a nested list
nested_list = [[20, 41, 42], [10, 14, 27], [7, 43, 44]]
# Accessing an element in a nested list
# "print("Element at row 1, column 1:", nested_list[20][20])"

Output:

Last element: -2
Elements from index 1 to 3 (exclusive): [32, -2]
Elements from the beginning up to index 3 (exclusive): [21, 32, -2]
Elements from index 2 to the end: [-2]

Array Methods

There are a number of built-in methods in Python lists and the array module that carry out particular operations on the list or array. Numerous methods are also available for NumPy arrays (ndarray), particularly for mathematical calculations.

Among the often used list techniques listed are:

Append(): The append() method adds one item to a list. The element is added to the end of the list. Programmers use “append” to add.

Insert():The insert() function in Python is used to add components or text to lists and text-based GUI widgets like Tkinter Entry and Text boxes. For lists, insert() adds a single item at an index and shifts the items before and after it to the right.

Extend(): Extend() adds all the entries from another iterable to a list. The iterable parameter is concatenated at the end of the list on which extend() is called.

Remove(): ython’s remove() method mostly deletes items by value from lists. Python removes the first occurrence of a value with list.remove(value).

Pop():The item at a specified index, or the last item if no index is provided, is removed and returned by the pop() function.

Clear(): Python’s clear() method removes all items from lists, dictionaries, and sets. Calling lists.clean() removes all list items.

Index(): An index in Python is the position number of an item in a list, tuple, or string. Indexing lets you access elements.

Count(): Python’s “count” method tracks occurrences or iterations and is available for numerous data types. People use count() with lists and strings. List.count(value) returns the number of times an element appears in a list. many times a value appears.

Sort(): Sort() is a basic Python list method that sorts a list. Instead of producing a new list, list.sort() adjusts the existing one.

Reverse(): In Python, “reverse” means altering the order of elements in a sequence using the reverse() method for lists, the built-in reversed() function for iterables, or slicing with a negative step.

Copy(): Python’s “copy” function duplicates an object or its contents, unlike variable assignment. Python duplicates the object reference when you assign one variable to another (e.g., b = a), so both variables point to the same memory item.

It also emphasises how to distinguish between functions like pop() and delete(), or append() and insert().

Code Example Using List Methods:

# Using a Python list
fruits = ["apple", "banana", "cherry"]
print("Original list:", fruits)
# Using append()
fruits.append("date")
print("After append('date'):", fruits)
# Using insert()
fruits.insert(1, "blueberry")
print("After insert(1, 'blueberry'):", fruits)
# Using remove()
fruits.remove("banana")
print("After remove('banana'):", fruits)
# Using pop() - removes and returns the last item
last_fruit = fruits.pop()
print("Popped item:", last_fruit)
print("List after pop():", fruits)
# Using sort()
fruits.sort()
print("After sort():", fruits)

Output:

Original list: ['apple', 'banana', 'cherry']
After append('date'): ['apple', 'banana', 'cherry', 'date']
After insert(1, 'blueberry'): ['apple', 'blueberry', 'banana', 'cherry', 'date']
After remove('banana'): ['apple', 'blueberry', 'cherry', 'date']
Popped item: date
List after pop(): ['apple', 'blueberry', 'cherry']
After sort(): ['apple', 'blueberry', 'cherry']

Array Exercises

Exercises intended to help students practise and apply their knowledge of arrays in Python and lists. From basic access and modification to more intricate processes, these activities cover a wide range of jobs [my prior response]. Review questions are frequently used as exercises to hone abilities such as discriminating between similar approaches or providing examples to clarify list methods.

Additionally, exercises can include working with NumPy array capabilities like creation functions, indexing, and slicing, or they can entail constructing arrays using random integers. Common exercise types include accessing and publishing items, dealing with nested lists, completing computations, iterating through arrays in Python, and utilising array functions, as we covered in our prior conversation.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index