LIST AND ITS METHODS
LIST
1. Lists are ordered collection of data items.
2. They store multiple items in a single variable.
3. List items are separated by commas and enclosed within square brackets [ ].
4. Lists are mutable (changeable), meaning we can alter them after creation.
5. Example:
list = ["Red", "Green", "Blue"]
print(list)
Output:
['Red', 'Green', 'Blue’]
List Index
Each item/element in a list has its own unique index. This index can be used to access any particular item from the list.
Example: colors = ["Red", "Green", "Blue", "Yellow", "Green"] # [0] [1] [2] [3] [4]
Positive Indexing:
Example: colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
print(colors[2])
Output: Blue
Negative Indexing:
Example: colors = ["Red", "Green", "Blue", "Yellow", "Green"] PRESENTED BY :
# [-5] [-4] [-3] [-2] [-1] MEENAKSHI
print(colors[-1]) ROLL NO. : 233211
Output: Green BRANCH : CSE
SECTION : A
SEMESTER : 3rd
SUBJECT :
append(): Adds an item to the end of the list.
Example:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
# Output: [1, 2, 3, 4]
extend(): Adds items of lists and other iterables to the end of the list.
Example:
color1 = ["violet", "indigo", "blue"]
color2 = ["green", "yellow", "orange", "red"]
colors.extend(color2)
print(colors)
Output: ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red’]
remove(): Removes the specified value from the list.
Example:
numbers = [10, 20, 30, 40, 50]
numbers.remove(30)
print(numbers)
Output: [10, 20, 40, 50]
pop():Returns and removes item present at the given index.
Example:
planets = ['Mercury', 'Venus', 'Earth', 'Mars’]
removed_planet = planets.pop(2)
print(planets)
Output: ['Mercury', 'Venus', 'Mars’]
index():Returns the index of the first matched item.
Example:
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
print(num.index(3))
Output: 3
count():Returns the count of the specified item in the list.
Example:
colors = ["violet", "green", "indigo", "blue", "green"]
print(colors.count("green"))
Output: 2
sort():Sorts the list in ascending/descending order.
Example:
num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort()
print(num)
Output: [1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]
reverse():Reverses the item of the list.
Example:
num = [1,2,3,4,5,6]
num.reverse()
print(num)
Output: [6,5,4,3,2,1]