List Methods in Python
In Python, a list is a built-in data structure that can hold an ordered collection of items.
A built-in- Data type that store set of Values. It can store elements of different types(integer, float, string etc.)
We use square brackets [] to create a list directly.
Example 1.
a = [1, 2, 3, 4, 5] # List of integers
b = ['apple', 'banana', 'cherry'] # List of strings
c = [1, 'hello', 3.14, True] # Mixed data types
print(a)
print(b)
print(c)
Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
Example 2.
a = list((1, 2, 3, 'apple', 4.5))
print(a)
b = list("ACC")
print(b)
Output
[1, 2, 3, 'apple', 4.5]
['G', 'F', 'G']
List Slicing
a = [10, 20, 30, 40, 50]
print(a[0])
print(a[-1])
print(a[1:4]) # elements from index 1 to 3
Output
10
50
[20, 30, 40]
List Method
- append(): Adds an element at the end of the list.
- extend(): Adds multiple elements to the end of the list.
- insert(): Adds an element at a specific position.
- clear(): removes all items.
- Sort(): Sorts the list.
- reverse():Reverses the order of the list.
- remove():Removes the first item with the specified value.
. copy(): Returns a copy of the list.
fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x)
Output
['apple', 'banana', 'cherry']
. count(): Returns the number of elements with the specified value.
fruits = ["apple", "banana", "cherry"]
x = fruits.count("cherry")
print(x)

No comments: