The list is one of the basic collection types in Python, which is used to store multiple objects using a single variable. Lists are dynamic and mutable, which means the objects in a list can be changed and the list can grow or shrink.
List objects in Python are not implemented using any linked list concept but using a variable-length array. The array contains references to objects it is storing. The pointer of this array and its length are stored in the list head structure, which is kept up to date as objects are added or deleted from a list. The behavior of such an array is made to appear like a list but in reality, it is not a real list. That is why some of the operations on a Python list are not optimized. For example, inserting a new object into a list and deleting objects from a list will have a complexity of n.
To rescue the situation, Python provides a deque data type in the collections built-in module. The deque data type provides the functionality of stacks and queues and is a good alternative option for cases when a linked list-like behavior is demanded by a problem statement.
Lists can be created empty or with an initial value using square brackets. Next, we present a code snippet that demonstrates how to create an empty or non-empty list object using only the square brackets or using the list object constructor:
e1 = [] #an empty list
e2 = list() #an empty list via constructor
g1 = ['a', 'b'] #a list with 2 elements
g2 = list(['a', 'b']) #a list with 2 elements using a \constructor
g3 = list(g1) #a list created from a list
The details of the operations available with a list object, such as add, insert, append, and delete can be reviewed in the official Python documentation. I have already covered these in older posts.
0 comments:
Post a Comment