How do you use arrays and lists in Python?
In Python, arrays and lists are both data structures used to store multiple values. Arrays are a fixed-length data structure containing elements of the same type, while lists are variable-length and can contain elements of different types. Here are some common operations for arrays and lists:
- Create arrays and lists.
- You can create an array using the array function of the array module, specifying the type of elements.
- Lists can be created directly using square brackets [], and can include elements of different types.
- Example code:
- Create an array
arr = array.array(‘i’, [1, 2, 3, 4, 5])
Create a list
lst = [1, 2, ‘a’, ‘b’, True]
- Accessing elements in an array and a list.
- Access elements using indexes, starting from 0.
- Get partial elements using slicing.
- Sample code:
- print the first element of the array
print the elements in the list with indexes 2 to 3 - Update array and list elements.
- Assign values using an index to modify elements at a specific position.
- Example code:
- arr[0] = 10 # Change the first element to 10
lst[2] = ‘c’ # Change the element at index 2 in the list to ‘c’ - Add elements to an array and a list.
- Add elements to the end of an array using the append method.
- Add elements to the end of a list using the append method.
- Example code:
- Add the element 6 to the end of the array
Add the element ‘d’ to the end of the list - Remove array and list elements.
- Use the remove method of an array to delete the first matching element.
- Use the remove method of the list to delete the first matching element.
- Delete the element at the specified position using the del keyword.
- Example code:
- – Remove the first occurrence of the element ‘3’ from the array.
– Remove the first occurrence of the element ‘b’ from the list.
– Delete the element at index 0 from the list.
These are the basic uses of arrays and lists, with many other operations and methods that can be explored and used.