Lists in Python are dynamic sized arrays, which makes it a robust tool. Python proposes a range of composite data types, and List is one of them. Lists are ordered collections that have a definite count.
Lists are mutable; therefore, it can be modified after they are created. A list can have different data types like Booleans, Objects, Integers, Strings, even Lists, and Objects. Let’s see how to create a list in Python.
Python create list
To create a list in Python, use the square bracket ([ ]). Place the sequence inside the square bracket, and the list is created.
In other words, a list can be created by placing all the items inside the square brackets [ ], separated by commas.
Create an empty list
To create an empty list in Python, define the empty square brackets, and your empty list is ready.
# app.py empty_list =  print(empty_list)
Create a list of numbers
To create a numbered list, write a numbered sequence inside the square brackets.
# app.py num_list = [18, 19, 21] print(num_list)
[18, 19, 21]
Create a list with mixed data types
You can create a list with mixed data types like boolean, string, integer, etc.
# app.py mixed_list = [11, 'Eleven', True] print(mixed_list)
[11, 'Eleven', True]
Create a multi-dimensional list
A multi-dimensional list means a list inside a list. Let’s define one.
# app.py mul_dim_list = [[18, 19], 21, [29, 46]] print(mul_dim_list)
[[18, 19], 21, [29, 46]]
Creating a list with multiple distinct or duplicate elements
Python list can contain duplicate values. Let’s define a list with duplicate values.
# app.py dup_list = [11, 21, 19, 21, 46, 21] print(dup_list)
[11, 21, 19, 21, 46, 21]
How to add elements in the List
To add an element to the list, use the append() method. The append() method adds a single element, and the extend() method adds multiple elements in the list.
# app.py add_list = [11, 19, 21] add_list.append(46) print(add_list) add_list.extend([29, 18]) print(add_list)
[11, 19, 21, 46] [11, 19, 21, 46, 29, 18]
In the first example, we use the append() method to add one element and then use the extend() method to insert multiple elements in the list.
To insert an item in the specific location of the list, use the insert() function. The list insert() function inserts an item to the list at the specified index. The list.insert() function doesn’t return anything, so it returns None. What it does is that it only updates the current list.
# app.py ins_list = [11, 19, 21] ins_list.insert(3, 46) print(ins_list)
[11, 19, 21, 46]
That is it for this tutorial.