Array
Practice Questions
Arrays Using List
Arrays in python can also be implemented using lists, which are dyanmic arrays which can grow and shrink.
List in Python is internally a dynamic array which can grow and shrink. Initially it can be created empty or with a fixed capacity and based on the elements getting added or removed, the capacity can be increased or decreased respectively.
When an element is added to an empty list in Python, a block of memory is allocated and element is added at index position 0. The remaining memory is considered to be reserved space which will be used later for addition or insertion of elements.
If you are looking at the source code for an application that allows users to create and use shopping lists for the grocery store, you might find code like this:
|
grocery = ["apples", "bananas", "cucumbers", "dates", "strawberries"] |
This array happens to contain five strings, each representing something that Alex might buy at the supermarket.
We begin counting the index at 0. So for our example array, "apples" is at index 0, and "strawberries" is at index 4.
apples
|
bananas
|
cucumbers
|
dates
|
strawberries
|
0 1 2 3 4
Adding an element into the array can be done using an append method in list:
Now the list becomes:
apples
|
bananas
|
cucumbers
|
dates
|
strawberries
|
oranges
|
Now you can try creating a list and append some items into the list.
Try here>>>