Python List Methods
list_name.append(item)
list_name.insert(index, item)
list_name.remove(item)
list_name.pop(index)
Items जोड़ना
append() एक single item को O(1) time में अंत में जोड़ता है, insert(i, x) किसी item को एक specific position पर रखता है (उसके बाद के सब elements को shift करके), और extend() दूसरे iterable के items को एक-एक करके merge करता है — extend(other_list), append(other_list) से बिल्कुल अलग है, जो पूरी list को एक ही element के रूप में nest कर देता।
उदाहरण: Adding Items
items = [1, 2]
items.append(3) # adds 3 to the end
items.insert(0, 0) # inserts 0 at position 0, shifting the rest right
items.extend([4, 5]) # adds each item of the list individually
print(items)
Items हटाना
remove(value) पहली matching value को हटाता है और अगर वह न मिले तो ValueError raise करता है, pop(index) उस position के item को हटाकर लौटा भी देता है (default में आखिरी item), और clear() पूरी list को खाली कर देता है — तीनों में से सिर्फ pop() ही है जो आपको हटाई गई चीज़ वापस देता है।
उदाहरण: Removing Items
items = [1, 2, 3, 2]
items.remove(2) # removes only the first matching 2
last = items.pop() # removes and returns the last item
print(items, last)
Items ढूँढना
index(value) किसी value के पहले occurrence की position लौटाता है (न मिलने पर ValueError raise करता है), जबकि count(value) बताता है कि वह कितनी बार आती है — जब आपको किसी item का सटीक location खोजने से पहले उसका होना confirm करना हो, तो दोनों साथ काम आते हैं।
उदाहरण: Finding Items
items = [1, 2, 3, 2]
print(items.index(2)) # position of the first 2
print(items.count(2)) # how many times 2 appears
Sorting और Reversing
sort() हर element के natural ordering (या किसी custom key function) का उपयोग करके list को in place rearrange करता है और None लौटाता है, इसीलिए 'my_list = my_list.sort()' एक classic bug है; reverse() बिना किसी comparison logic के मौजूदा क्रम को सीधे पलट देता है।
उदाहरण: Sorting and Reversing
items = [3, 1, 2]
items.sort() # sorts in place, returns None
print(items)
items.reverse() # flips the current order
print(items)
Lists को Copy करना
new_list = old_list लिखने पर सिर्फ reference copy होता है, इसलिए किसी भी नाम से किया गया बदलाव उसी underlying list को असर करता है — copy() (या list[:] का slice trick) एक genuinely अलग list बनाता है, हालाँकि उसके अंदर की nested lists अब भी shared रहती हैं (shallow copy)।
उदाहरण: Copying Lists
original = [1, 2, 3]
copy = original.copy() # creates a separate list, not just another reference
copy.append(4)
print(original, copy) # original is unaffected
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: