Top Ad unit 728 × 90

Libreoffice

Libreoffice Writer

List Methods in Python

 



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.


fruits = ["apple", "banana", "cherry"]

fruits.append("orange")

print(fruits)


Output

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



  • extend()Adds multiple elements to the end of the list.


fruits = ['apple', 'banana', 'cherry']

cars = ['Ford', 'BMW', 'Volvo']

fruits.extend(cars)

print(fruits)


Output

['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']


  • insert(): Adds an element at a specific position.

fruits = ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")

print(fruits)


Output

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


  • clear(): removes all items.

fruits = ["apple", "banana", "cherry"]

fruits.clear()

print(fruits)


Output

[]


  • Sort()Sorts the list.

cars = ['Ford', 'BMW', 'Volvo']

cars.sort()

print(cars)



Output


['BMW', 'Ford', 'Volvo']


  • reverse():Reverses the order of the list.

fruits = ['apple', 'banana', 'cherry']

fruits.reverse()

print(fruits)


Output

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


  • remove():Removes the first item with the specified value.

fruits = ['apple', 'banana', 'cherry']

fruits.remove("banana")

print(fruits)



Output

['apple', 'cherry']


    . pop():Removes the element at the specified position.


fruits = ['apple', 'banana', 'cherry']

fruits.pop(1)

print(fruits)


Output

['apple', 'cherry']


    . 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)



Output


1


    . index()Returns the index of the first element with the specified value.


fruits = ['apple', 'banana', 'cherry']

x = fruits.index("cherry")

print(x)


Output

2


List Methods in Python Reviewed by ADcomputercampus on February 24, 2026 Rating: 5

No comments:

Contact Form

Name

Email *

Message *

Powered by Blogger.