List Functions
List Functions
Lists are one of the most versatile and commonly used data structures in Python.
They are used to store collections of items, and Python provides various built-in
functions to manipulate and interact with lists efficiently. In this guide, we will
explore the essential list functions in Python and learn how to use them
effectively.
Example:
Code
script.py
1
2
fruits = ['apple', 'banana', 'orange', 'kiwi']
print(len(fruits)) # Output: 4
Execute code
Example:
Code
script.py
1
2
3
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
Execute code
Example:
Code
script.py
1
2
3
4
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
Execute code
Example:
Code
script.py
1
2
3
fruits = ['apple', 'banana', 'kiwi']
fruits.insert(1, 'orange')
print(fruits) # Output: ['apple', 'orange', 'banana', 'kiwi']
Execute code
Example:
Code
script.py
1
2
3
numbers = [1, 2, 3, 4, 2]
numbers.remove(2)
print(numbers) # Output: [1, 3, 4, 2]
Execute code
Example:
Code
script.py
1
2
3
4
fruits = ['apple', 'banana', 'orange']
removed_fruit = fruits.pop(1)
print(removed_fruit) # Output: 'banana'
print(fruits) # Output: ['apple', 'orange']
Execute code
Example:
Code
script.py
1
2
3
numbers = [1, 2, 3, 4]
numbers.clear()
print(numbers) # Output: []
Execute code
Example:
Code
script.py
1
2
3
fruits = ['apple', 'banana', 'kiwi', 'banana']
index = fruits.index('banana')
print(index) # Output: 1
Execute code
Example:
Code
script.py
1
2
3
fruits = ['apple', 'banana', 'kiwi', 'banana']
count = fruits.count('banana')
print(count) # Output: 2
Execute code
Example:
Code
script.py
1
2
3
numbers = [3, 1, 2, 5, 4]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4, 5]
Execute code
Example:
Code
script.py
1
2
3
fruits = ['apple', 'banana', 'kiwi']
fruits.reverse()
print(fruits) # Output: ['kiwi', 'banana', 'apple']
Execute code
Example:
Code
script.py
1
2
3
numbers = [1, 2, 3]
numbers_copy = numbers.copy()
print(numbers_copy) # Output: [1, 2, 3]
Execute code
Conclusion
List functions in Python provide a powerful set of tools for manipulating and
managing lists. Understanding these functions allows you to efficiently work with
lists and perform various operations such as adding, removing, searching, and
sorting elements.
Remember that lists are mutable, meaning you can modify them directly using these
functions. Keep in mind the differences between modifying a list in place and
creating a new list to ensure the desired behavior in your code.