Python List Reverse():
-> The reverse() method is a built-in method in Python that reverses the order of elements in a list.
-> This method modifies the original list and does not return a new list, which makes it an efficient way to perform the reversal without unnecessary memory uses.
a = [1, 2, 3, 4, 1, 2, 6]
a.reverse()
print(a)
Output:
[6, 2, 1, 4, 3, 2, 1]
Sort():
-> The sort() method in Python is used to arrange the elements of a list in a specific order.
-> It works only on lists, modifies the original list in place, and does not return a new list.
a = [5, 3, 8, 1, 2]
a.sort()
print(a)
Output:
[1, 2, 3, 5, 8]
sort vs sorted:
sort --> in-place sorting: The original list gets modified.
sorted --> returns a new list with elements sorted.
Copy():
-> The copy() method in Python is used to create a shallow copy of a list.
-> This means that the method creates a new list containing the same elements as the original list but maintains its own identity in memory.
-> It's useful when you want to ensure that changes to the new list do not affect the original list and vice versa.
a = [1, 2, 3]
b = a.copy()
print('a:', a)
print('b:', b)
Output:
a: [1, 2, 3]
b: [1, 2, 3]
Count():
-> The count() method in Python returns the number of times a specified substring appears in a string.
-> It is commonly used in string analysis to quickly check how often certain characters or words appear.
s = "hello world"
res = s.count("o")
print(res)
s = "hello world"
res = s.count("o")
print(res)
Output:
2
Top comments (0)