- Python Design Patterns - Home
- Python Design Patterns - Introduction
- Python Design Patterns - Gist
- Model View Controller Pattern
- Python Design Patterns - Singleton
- Python Design Patterns - Factory
- Python Design Patterns - Builder
- Python Design Patterns - Prototype
- Python Design Patterns - Facade
- Python Design Patterns - Command
- Python Design Patterns - Adapter
- Python Design Patterns - Decorator
- Python Design Patterns - Proxy
- Chain of Responsibility Pattern
- Python Design Patterns - Observer
- Python Design Patterns - State
- Python Design Patterns - Strategy
- Python Design Patterns - Template
- Python Design Patterns - Flyweight
- Python Design Patterns - Abstract Factory
- Python Design Patterns - Object Oriented
- Object Oriented Concepts Implementation
- Python Design Patterns - Iterator
- Python Design Patterns - Dictionaries
- Python Design Patterns - Lists Data Structure
- Python Design Patterns - Sets
- Python Design Patterns - Queues
- Python Design Patterns - Strings & Serialization
- Python Design Patterns - Concurrency
- Python Design Patterns - Anti Pattern
- Python Design Patterns - Exception Handling
Python Design Patterns Resources
Python Design Patterns - List Data Structure
The Lists data structure is a versatile datatype in Python, which can be written as a list of comma separated values between square brackets.
Syntax
Here is the basic syntax for the structure −
List_name = [ elements ];
If you observe, the syntax is declared like arrays with the only difference that lists can include elements with different data types. The arrays include elements of the same data type. A list can contain a combination of strings, integers and objects. Lists can be used for the implementation of stacks and queues.
Lists are mutable. These can be changed as and when needed.
Example - How to implement lists?
The following program shows the implementations of lists −
main.py
my_list = ['p','r','o','b','e'] # Output: p print(my_list[0]) # Output: o print(my_list[2]) # Output: e print(my_list[4]) # Error! Only integer can be used for indexing # my_list[4.0] # Nested List n_list = ["Happy", [2,0,1,5]] # Nested indexing # Output: a print(n_list[0][1]) # Output: 5 print(n_list[1][3])
Output
The above program generates the following output −
p o e a 5
The built-in functions of Python lists are as follows −
Append()− It adds element to the end of list.
Extend()− It adds elements of the list to another list.
Insert()− It inserts an item to the defined index.
-
Remove()− It deletes the element from the specified list.
Reverse()− It reverses the elements in list.
sort() − It helps to sort elements in chronological order.