Lists in Python
A list in Python is a versatile data structure that allows you to store multiple items in a single variable.
These items can be of different data types (e.g., integers, strings, floats, etc.). Lists are mutable, meaning
their elements can be changed after creation.
Key Features of Lists
Ordered: Elements are stored in a specific sequence.
Mutable: You can modify, add, or remove elements.
Heterogeneous: Can store elements of different data types.
Indexed: Elements can be accessed using their index (starting from 0).
Common List Functions and Methods
Here are some commonly used functions and methods for working with lists:
1. Adding Elements
append(element): Adds an element to the end of the list.my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
insert(index, element): Inserts an element at a specific position.my_list = [1, 2, 3]
my_list.insert(1, 5) # [1, 5, 2, 3]
extend(iterable): Adds all elements of an iterable (e.g., another list) to the end.my_list = [1, 2]
my_list.extend([3, 4]) # [1, 2, 3, 4]
2. Removing Elements
remove(element): Removes the first occurrence of the specified element.my_list = [1, 2, 3, 2]
my_list.remove(2) # [1, 3, 2]
pop(index): Removes and returns the element at the specified index (default is the last element).my_list
= [1, 2, 3]
my_list.pop(1) # [1, 3]
clear(): Removes all elements from the list.my_list = [1, 2, 3]
my_list.clear() # []
3. Accessing Elements
Indexing: Access elements using their index.my_list = [10, 20, 30]
print(my_list[1]) # 20
Slicing: Access a subset of the list.my_list = [10, 20, 30, 40]
print(my_list[1:3]) # [20, 30]
4. Other Useful Methods
len(list): Returns the number of elements in the list.my_list = [1, 2, 3]
print(len(my_list)) # 3
sort(): Sorts the list in ascending order (in-place).my_list = [3, 1, 2]
my_list.sort() # [1, 2, 3]
reverse(): Reverses the order of elements in the list.my_list = [1, 2, 3]
my_list.reverse() # [3, 2, 1]
index(element): Returns the index of the first occurrence of the element.my_list = [1, 2, 3]
print(my_list.index(2)) # 1
count(element): Counts the occurrences of an element in the list.my_list = [1, 2, 2, 3]
print(my_list.count(2)) # 2
5. List Comprehension
A concise way to create lists.
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
These methods and functions make lists a powerful and flexible tool in Python programming!