Selection in Array Python

Data Structure >   Array >   Selection  

Long Question

137


Answer:

In Python, you can perform selection (i.e., accessing a specific element in an array) using the index of the element.

Here's an example:


arr = [1, 2, 3, 4, 5]

# Accessing the first element of the array
print(arr[0])

# Accessing the third element of the array
print(arr[2])

This will output 1 and 3, respectively.

You can also use negative indices to access elements from the end of the array:


arr = [1, 2, 3, 4, 5]

# Accessing the last element of the array
print(arr[-1])

# Accessing the second to last element of the array
print(arr[-2])

This will output 5 and 4, respectively.

If you try to access an index that is out of range (i.e., larger than or equal to the length of the array), you will get an IndexError:


arr = [1, 2, 3, 4, 5]

# This will cause an IndexError
print(arr[5])

Output:


IndexError: list index out of range


This Particular section is dedicated to Question & Answer only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.