Python List Methods | Complete Explanation with Examples

Python List Methods — Complete Guide

Python lists come with many built-in methods to manipulate and work with the data efficiently. Here, you will learn each important list method with examples and explanations.

Python lists में कई built-in methods होते हैं जो डेटा को आसानी से manipulate करने में मदद करते हैं। यहाँ हर महत्वपूर्ण method का example और explanation दिया गया है।

append()

Adds a single element to the end of the list.

List के अंत में एक element जोड़ता है।

fruits = ['apple', 'banana']
fruits.append('cherry')
print(fruits)

Output:

['apple', 'banana', 'cherry']

extend()

Adds all elements from another iterable (like list) to the end.

दूसरे iterable के सभी elements list के अंत में जोड़ता है।

fruits = ['apple', 'banana']
fruits.extend(['cherry', 'orange'])
print(fruits)

Output:

['apple', 'banana', 'cherry', 'orange']

insert()

Inserts an element at a specified index.

निश्चित index पर एक element insert करता है।

fruits = ['apple', 'banana']
fruits.insert(1, 'cherry')
print(fruits)

Output:

['apple', 'cherry', 'banana']

remove()

Removes the first matching element by value.

पहले matching element को value से हटाता है।

fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits)

Output:

['apple', 'cherry']

pop()

Removes and returns element at given index (default last).

दिए गए index पर element हटाता है और लौटाता है (default last)।

fruits = ['apple', 'banana', 'cherry']
item = fruits.pop(1)
print(item)
print(fruits)

Output:

banana
['apple', 'cherry']

clear()

Removes all elements from the list.

List के सभी elements हटा देता है।

fruits = ['apple', 'banana', 'cherry']
fruits.clear()
print(fruits)

Output:

[]

index()

Returns the index of the first matching element.

पहले matching element का index लौटाता है।

fruits = ['apple', 'banana', 'cherry']
print(fruits.index('banana'))

Output:

1

count()

Returns the number of times a value appears in the list.

List में किसी value के कितनी बार होने की संख्या लौटाता है।

numbers = [1, 2, 2, 3, 2]
print(numbers.count(2))

Output:

3

sort()

Sorts the list in ascending order (in-place).

List को ascending order में sort करता है (in-place)।

numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)

Output:

[1, 2, 3, 4]

reverse()

Reverses the elements of the list (in-place).

List के elements को उल्टा कर देता है (in-place)।

numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers)

Output:

[4, 3, 2, 1]

copy()

Returns a shallow copy of the list.

List की shallow copy लौटाता है।

fruits = ['apple', 'banana']
copied = fruits.copy()
print(copied)

Output:

['apple', 'banana']