Lists in Python | Create List, Example

Sequences are the most basic type of data structures in Python. The data structure provides us with a style to store multiple data or values in the memory.

A sequence is a data type that represents a group or collection of elements or items. It allows us to store multiple items in an organized and efficient fashion.

A sequence data type allows us to perform different operations such as indexing, slicing, multiplying, adding, removing, and membership checking.

In Python programming language, strings, lists, tuples, sets, and dictionaries are very important sequence or collection data types.

In this tutorial, we will understand the significant role of lists in Python to store multiple elements of different types, and possible operations that we can perform on the list with the help of various methods.

What is List in Python?


A Python list is basically an ordered sequence or collection of elements. In other words, a list is a container that holds several elements. Each item or value that is inside a list is called an element which can be of any type (like string, float, integer, object, etc.).

Basically, a list can hold any primitive data type, sequence data type, or a combination of several data types. It can even hold a list as an element. For example, we can have a list which is a mix of different element types, such as strings, numbers, and another list itself.

Lists handle a large amount of heterogeneous data. All the elements in the list are assigned to a single variable. Lists do not use separate variable for storing each element which is less efficient and more error prone when we perform some operations on these elements.

In Python, list is a flexible data type that we can modify it according to requirement. We can make updates in the already existing list without creating a new list object. That’s why, list is mutable data type.

Python list data structure is similar to array data structure in other programming languages. The main difference is that list is collection of heterogeneous data elements. We can store data of any type in it. While, array in other programming language like Java can hold only one type of data.

Moreover, an array is static data structure, meaning that we need to specify its size before using it. While, list can dynamically increase or decrease itself when we add or delete elements from the list.

Why do We Need List in Python?


We know a variable can hold a single value. For example:

num = 20

Sometimes, we need to store more than that. For example, in the real world, we often make lists like daily to-do lists, a list of food and vegetables, a guest list for wedding, a list of players of football team, etc. If we make a list, we will have to define multiple variables to store values of the list, which makes the code clumsy.

To overcome this problem, Python introduces a flexible data storage format called lists in which we can store multiple values in the list and can assign to a single variable. We can easily add, delete, and update values from the list.

Characteristics of Python Lists


In Python, a list is a sequence data structure that provides almost all the functionalities offered by the array data structure. There are the following characteristics of lists in Python.

Characteristics of Lists in Python

1. Linear data structure: A list is a linear data structure in which Python store elements in the contiguous memory locations in a linear order one after the other.


2. Ordered: A list is an order collection of elements. It preserves our insertion order in which we have placed elements in the order.


3. Duplicate elements: A list allows any number of duplicate elements.

4. Mutable: In Python, list is a mutable data type, meaning we can make an update or change in the existing list object. We do not need to create a new list object every time while updating the existing list object.


5. Flexibility: In Python, lists offer flexibility or scalability to the user because we can modify or update its elements according to our requirement. We can easily add, remove, or alter the list element at runtime. A list expands or shrinks in the computer memory as per requirement.

6. Declaration: Declaration of lists in Python is quite easy because we do not need to declare the list object before using it. When we assign values in the square brackets ([ ]), the list automatically declared.


7. Heterogeneous elements: One of the biggest advantages of using a list in Python is that we can construct a list of heterogeneous elements. We can insert elements or values of different data types, such as string, numbers, object, or even another list as an element, etc. in a single list.

The elements of different data types take the space in the computer memory in accordance with the value of a particular type stored in the list.

8. Functionality: Python list date type provides many functions that allow us easily to perform different set of operations instead of writing long code. We can use dir(list_name) to gain a list of functions provided by a list.


9. Dynamic: List data type in Python is dynamic in nature, meaning that we do not declare the size of a list while creating a list. The list consumes memory space in accordance with the requirement.

The list automatically expands when we insert an element or data at runtime. It shrinks automatically when we remove or delete an element from the list at runtime.

10. Multidimensional: List can also be used as a multidimensional data structure. With a multidimensional list, we can easily construct a matrix and we can perform different matrix operations on the list.


11. Easy to add elements: We can easily insert values or data in the list. Lists in Python provide different methods, like append, insert, and extend to insert values to the list.

Using input() method, we can take input value from the user and can add the entered input value to the list using one of these methods.

12. Easy to display elements: We can easily display different values stored on the list. Even we can display values of list without iterating over the list.

To display in the simple style, we simply need to write print statement and to pass the list object to the print() function, which we want to print on the console.


13. Easy to use: The use of list data type is a very easy as compared to other data types. It consumes memory dynamically as well as provides various methods to provide an easy way to write the program code.

14. Availability of various methods: Python list provides a unique set of inbuilt methods. Using them, we can easily perform various tasks or operations by just calling these methods with the list object.

For example, if you want to sort elements of a list, you do not need to write the complete code for sorting elements. You simply need to call the inbuilt sort() method with the list object, which you want to sort.

Creating Lists in Python


We create lists in Python using square brackets [ ]. To create a list, enclose elements or values in square brackets separated by commas (,) and assign it a user-defined variable.

The general syntax to declare or create a list is as follows:

list_name = [element_1, element_2, element_3, . . . . ., element_n]
or,
list_name = [value1, value2, value3, . . . . ., valuen]

Here, list_name is the name of the list variable and element_1, element_2, . . . . ., element_n are list of values assigned to the list.

These elements, values, or data can be homogeneous (i.e. of same type) or heterogeneous (i.e. of different types) in accordance with need.

Each element has an index position or location that ranges from 0 to (n-1) where n is the total number of elements in the list. In the above syntax, opening and closing square brackets just represent in starting and ending of the list.

Let’s take an example in which we will create an empty list. A list that does not contain elements is called empty list.

Example:

# Python program to create an empty list.
empty_list = [] 
print(type(empty_list))
Output:
      <class 'list'>

In this example, we have created an empty list with variable name empty_list that contains no elements. The variable empty_list is of type list. We can determine the type of variable by passing the name of variable as an argument to type() function.

Creating Lists by Assigning Values


There are several ways to create lists in Python. The easiest way to create a list is by simply assigning a set of values to the list using an assignment operator.

Let’s take some valid examples in which we will create lists and assign a set of values to the list variables.

Example 1: List with integer values

# Creating a list of 5 integer elements or values and assigning it to a variable.
num_list = [20, 30, 40, 50, 60]
print(num_list)
Output:
       [20, 30, 40, 50, 60]

In this example, we have created a list object of five integer values and stored it into a variable named num_list. Then, we have displayed it in a console. You can also observe in the output that the list has maintained the insertion order in which we have placed elements in the order.

Example 2: List with string values

# Creating a list of 5 string elements or values and assigning it to a variable.
string_list = ["John", "Bob", "Harry", "Mark", "Deep"]
print(string_list)
Output:
      ['John', 'Bob', 'Harry', 'Mark', 'Deep']

Example 3: List with mixed data type

# Creating a list of 4 heterogeneous values and assigning it to a variable.
mixed_list = ["John", 25, 30, 40.45]
print(mixed_list)
Output:
      ['John', 25, 30, 40.45]

In this example, we have created a list of four heterogeneous values (string, integers, and float) and stored it into a variable named mixed_list. Then, we have displayed it on a console.

Example 4: List with nested list

# Creating a list of 5 heterogeneous values and storing it into a variable.
nested_list = ["John", 25, 30, 30.45, [1, 2, 3]]
print(nested_list)
Output:
      ['John', 25, 30, 30.45, [1, 2, 3]]

In the preceding example, we have created a nested list. A nested list is a list that contains another list. However, a nested list is still considered as a single element. Therefore, the length of list is 5.

Example 5: List of characters

# Creating a list of 5 characters and storing it into a variable char_list.
char_list = ['a', 'b', 'c', 'd']
print(char_list)
Output:
       ['a', 'b', 'c', 'd']

We can also create a long list containing several items by splitting the list across many lines. Look at the below example.

Example 6:

# Creating a long list of integer values into several lines.
long_list = [0, 3, 6, 9, 12,
             15, 18, 21, 24,
             27, 30, 33, 37, 40]
print(long_list)
Output:
       [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 37, 40]

Input a List from the User


We can add elements, values, or data in the list by taking inputs from the user. To get inputs from the user, we generally use an inbuilt input() function provided by Python.

This function simply displays a message and prompts the user to enter a valid input. Any input provided by the user from the keyboard is as string.

To create a list of numbers, we need to convert that string value into integer values with the help of int() function. We can use different functions with input() function to input elements in the lists. Let’s take an example of it to understand better.

Example 7:

# Python program to enter integer values in the list by using insert() function.
num = int(input("Enter the number of elements: "))
list = [] # creating an empty list.
for i in range(num):
    num_list = int(input("Enter integer value: "))
    list.insert(i, num_list)
print("Entered list is:",list)
Output:
      Enter the number of elements: 4
      Enter integer value: 20
      Enter integer value: 30
      Enter integer value: 40
      Enter integer value: 50
      Entered list is: [20, 30, 40, 50]

In this example program, we have taken 4 values from the user and inserted those values into a list. The second line displays a message for the user to enter the number of elements in the list and stored the value into a variable named num.

The third line creates an empty list with name list. In the fourth line, we have used for loop to iterate over 0 to 4 and allow the user to input four values to the list num_list.

Then, we have called the insert(index, value) function to insert multiple elements at the ith index in the list num_list. At last, we have displayed the created list with multiple values.

Multidimensional Lists in Python


We can make a multidimensional list by nesting lists inside other lists. A multidimensional list can be used to store a matrix or table of information. For example, we can create a 3 * 3 matrix by assigning a list of lists to a variable. Look at the below example code.

Example 8:

matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
print(matrix)
Output:
       [[2, 4, 6], [8, 10, 12], [14, 16, 18]]

Unpacking List Values in Python


We can store or assign a list values to variables by using assignment operator. Let us understand it with the help of an example.

Example 9:

n1, n2 = [10, 20]
print(n1)
print(n2)
Output:
       10
       20

In this example, we have assigned 10 to a variable n1 and 20 to a variable n2. This is called unpacking in Python. What happens if we store with more values? Let’s understand it with the following example.

Example 10:

n1, n2 = [10, 20, 30]
print(n1)
Output:
       n1, n2 = [10, 20, 30]
       ValueError: too many values to unpack (expected 2)

This error shows that there are more values to unpack. Let’s understand another example.

Example 11:

n1, n2, n3 = [10, 20]
print(n1)
Output:
      n1, n2, n3 = [10, 20]
      ValueError: not enough values to unpack (expected 3, got 2)

This error shows that there should be more values in the list to unpack.

Concept of Mutable Lists in Python


Lists in Python are mutable objects. It means that we can change or modify elements in the list without creating a new list. We can change the value of an element in a list with the help of an assignment operator.

On the other hand, strings are immutable objects in Python. Let’s take an example in which we will modify a value of an element in the existing list.

Example 12:

num = [20, 30, 35.5, 50, 60]
print("Original list: ",num)
num[2] = 40
print("Modified list:",num)
Output:
       Original list:  [20, 30, 35.5, 50, 60]
       Modified list: [20, 30, 40, 50, 60]

In this example, we have modified a value in the list. The second value of num, which is 35.5, is now changed to 40. You can consider a list as a relationship between elements and indices. We call it as mapping, meaning that each index “maps” to one element in the list.

If we assign a list to a variable, Python never creates a new list. For example:

X = Y = [20, 30, 40] # Here, both names are pointing to the same list.
X = [1, 2, 3, 4, 5]

Y = X # Here, both names are pointing to the same list.
X = [2, 3, 4, 5]; Y = [6, 7, 8, 9] # Here, both are independent lists.

Advantages of Lists in Python


There are the following advantages of using lists in Python. They are:

  • Lists store elements in ordered in which we have provided. They preserve our insertion order.
  • Lists allow to add any number of duplicate elements.
  • One of the outstanding advantages of using lists is that we can store elements of different data types on a single list.
  • Python does not need to create a new list object every time while updating the existing list.
  • Lists provide the flexibility to the user. We can easily add or remove an element in the list at runtime.
  • They provide various useful functions to perform a different set of operations.
  • List is easy to use as compared to other data types.

In this tutorial, you have learned about lists in Python with various example programs. Hope that you will have understood the basic points of lists and practiced all example programs. In the next tutorial, we will learn how to access and display elements in the list.
Thanks for reading!!!