Here are some of the most common operations you can perform on a list in Python:
- Creating a list: To create a new list, simply enclose a comma-separated sequence of values in square brackets [].
Example:
cssmy_list = [1, 2, 3, 4, 5]
- Accessing elements: To access an element in a list, use its index within square brackets. Python uses zero-based indexing, so the first element is at index 0.
Example:
pythonprint(my_list[0]) # Output: 1
- Slicing: To retrieve a sublist of a list, use slicing notation with the start and end index separated by a colon. The slice includes the element at the start index and excludes the element at the end index.
Example:
pythonprint(my_list[1:3]) # Output: [2, 3]
- Modifying elements: You can change the value of an element in a list by assigning a new value to its index.
Example:
scssmy_list[3] = 10
print(my_list) # Output: [1, 2, 3, 10, 5]
- Adding elements: To add an element to the end of a list, use the append() method. To insert an element at a specific index, use the insert() method.
Example:
scssmy_list.append(6)
print(my_list) # Output: [1, 2, 3, 10, 5, 6]
my_list.insert(2, 4)
print(my_list) # Output: [1, 2, 4, 3, 10, 5, 6]
- Removing elements: To remove an element from a list, use the remove() method if you know the value of the element, or the del statement if you know the index.
Example:
pythonmy_list.remove(4)
print(my_list) # Output: [1, 2, 3, 10, 5, 6]
del my_list[1]
print(my_list) # Output: [1, 3, 10, 5, 6]
- Sorting: To sort the elements of a list, use the sort() method.
Example:
scssmy_list.sort()
print(my_list) # Output: [1, 3, 5, 6, 10]
- Reversing: To reverse the order of the elements in a list, use the reverse() method.
Example:
perlmy_list.reverse()
print(my_list) # Output: [10, 6, 5, 3, 1]
- Length: To get the number of elements in a list, use the len() function.
Example:
pythonprint(len(my_list)) # Output: 5
- Concatenation: To concatenate two or more lists, use the + operator.
Example:
scssmy_list2 = [7, 8, 9]
print(my_list + my_list2) # Output: [1, 3, 5, 6, 10, 7, 8, 9]
- Membership: To check if an element is in a list, use the in operator.
Example:
pythonprint(5 in my_list) # Output: True
print(15 in my_list) # Output: False
No comments:
Post a Comment