Accessing Python List Items | Different Ways Explained

Accessing Python List Items

You can access items in a Python list in many ways including by index, slicing, negative indexes, and looping through the list.

Python list में items को कई तरीकों से access किया जा सकता है जैसे index, slicing, negative index, और loop के द्वारा।

Example 1: Access by Positive Index
fruits = ['apple', 'banana', 'cherry']
print(fruits[0])

Access first element using index 0.

पहले element को index 0 से access करें।

Output:

apple
Example 2: Access by Negative Index
fruits = ['apple', 'banana', 'cherry']
print(fruits[-1])

Access last element using index -1.

अंतिम element को index -1 से access करें।

Output:

cherry
Example 3: Access a Range of Items with Slicing
fruits = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(fruits[1:4])

Access elements from index 1 up to but not including 4.

index 1 से 4 तक (4 को छोड़कर) elements access करें।

Output:

['banana', 'cherry', 'orange']
Example 4: Access Items from Start to Index
fruits = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(fruits[:3])

Access elements from start up to but not including index 3.

शुरू से लेकर index 3 तक (3 को छोड़कर) elements access करें।

Output:

['apple', 'banana', 'cherry']
Example 5: Access Items from Index to End
fruits = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(fruits[2:])

Access elements from index 2 to end.

index 2 से लेकर अंत तक elements access करें।

Output:

['cherry', 'orange', 'kiwi']
Example 6: Access Every Other Item (Step Slicing)
fruits = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(fruits[::2])

Access every 2nd element from the list.

List में हर दूसरे element को access करें।

Output:

['apple', 'cherry', 'kiwi']
Example 7: Reverse List Using Slicing
fruits = ['apple', 'banana', 'cherry']
print(fruits[::-1])

Access list elements in reverse order.

List के elements को उल्टे क्रम में access करें।

Output:

['cherry', 'banana', 'apple']
Example 8: Loop Through List Items
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

Print each item by looping through the list.

Loop से list के प्रत्येक item को print करें।

Output:

apple
banana
cherry
Example 9: Loop with Index and Item Using enumerate()
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
    print(i, fruit)

Print index and item using enumerate().

enumerate() से index और item दोनों print करें।

Output:

0 apple
1 banana
2 cherry
Example 10: Nested List Access
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[1][0])

Access element 3 from nested list at row 1, column 0.

Nested list में row 1 और column 0 का element access करें।

Output:

3