Let’s dive into the world of Python lists, a versatile and widely used data structure. These lists are perfect for storing collections of items, even if they’re of different data types. In this article, we’ll explore the Python list, from its basic syntax to advanced operations, all with the help of illustrations.
What is a List in Python?
In Python programming, a list is a built-in data structure used to store collections of items. It is a mutable data structure. It means you can change the list’s contents after creation. Lists are defined by enclosing comma-separated values within square brackets ‘[]’.
Python List can contain different data types, including integers, floats, strings, boolean, and other lists.
Example of List
my_list = [1, 2, 3, 'hello', True, 5.6]
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Characteristics of Lists
The following are the characteristics of Lists:
Ordered: List data structure to maintain the order of elements.
Mutable: List are mutable data structures. It means It can change the order of the list.
Allow Duplicates: List data structure allows duplicate data.
Creating a List in Python
In Python, creating a list is as simple as riding a motorbike. We can create a list by passing elements in square brackets separated by a comma.
The following program demonstrates “how we can create a simple list in Python.”
Program
# A list of three elements
ages = [35, 20, 21]
print(ages)
# Output: [19, 26, 29]
Output
[35, 20, 21]
Accessing Elements in the List
Python uses zero-based indexing, meaning the first element has an index of 0. We can access individual elements using their index values in a list. We can also use negative values to access the list in Python. Negative indexing starts at the end of the list. It means ‘-1’ accesses the last element of the list.
In Python, we can create a multidimensional list, which is a list within a list. In this section, we will access the multidimensional list by indexing.
Program
# Python program to demonstrate printing
# of complete multidimensional list
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20],[10,20,30,40,50]]
print(a)
print(a[0])
print(a[1])
print(a[2])
In Python, we can also take input from the user and store it as a string, integer, float, etc. However, in Python, the input is a string.
The following program demonstrates the Python list.
Program
string = input("Enter elements (Space-Separated): ")
lst = string.split()
print('The list is:', lst)
Output
Enter elements (Space-Separated): Rajj, Kumar, Harry, Potter
The list is: ['Raj,', 'Kumar,', 'Harry', ',', 'Potter']
Change List Items in the List
In Python programming, a List is a mutable data structure. This means we can change the list after it is created using various methods, such as direct assignment, slicing, and list methods.
Assignment
We can change the list using the assignment operator. First, select the list item using the index, then assign the new value to the list.
The following program demonstrates the assignment changes in the list.
We can also use slicing to change the list. First, we have to define the specific range for updating the list. Then, we define a new list with new values and assign those values to the old list.
Add Elements to a Python List using insert() method
Python append() method adds the item in the list at the end of the list. This is good but sometimes it does not fill our needs. There is one more method in Python language for inserting the element in the list at the specific position. The insert() method takes two arguments: the first one is position, and the second one is the value.
The following program demonstrates the Python list insert()method.
Program
# Python program to demonstrate
# Addition of elements in a List
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
List.insert(3, 12)
List.insert(0, 'Computer Program')
print("nList after performing Insert Operation: ")
print(List)
Program
Initial List:
[1, 2, 3, 4]
List after performing Insert Operation:
['Computer Program', 1, 2, 3, 12, 4]
Add Elements to a Python List using the extend() method
There is one more method in the Python list for adding the elements and adding two lists in Python. The extend() method is used for adding multiple lists in a single list. It adds the list at the end of the list.
The following program demonstrates the Python List extend() method.
Program
# Creating a List
List = [1, 2, 3, 4]
print("Initial List: ")
print(List)
List.extend([8, 'Harry', 'Potter', 'Hermoine'])
print("nList after performing Extend Operation: ")
print(List)
Output
Initial List:
[1, 2, 3, 4]
List after performing Extend Operation:
[1, 2, 3, 4, 8, 'Harry', 'Potter', 'Hermoine']
Reversing a List
We can reverse a whole list using the inbuilt method in Python language. There are many easy ways to do this task. However, we will use two methods for solving this problem: the reverse() method and the reversed() method.
Using the reverse() method: The following program demonstrates the reverse() method example in Python.
Program
# Reversing a list
mylist = [1, 2, 3, 4, 5, 6, 7,8,9,10]
mylist.reverse()
print(mylist)
Output
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Using the reversed() function: The reversed() function returns the reverse iterator, which can be converted to the list using a list() function.
In Python, we can iterate a list using a for loop. The following program demonstrates this list iterating.
Program
fruits = ['apple', 'banana', 'orange']
# iterate through the list
for fruit in fruits:
print(fruit)
Output
apple
banana
orange
Get the Length of the List
In Python, we can also get the length of the list using the len() function, which returns the length of the list as an integer.
The following program demonstrates the len() function in the list.
Program
my_list = [1, 2, 3, 4, 5,10,29,39,True, "work"]
length_of_list = len(my_list)
print("The length of the list is:", length_of_list)
Output
The length of the list is: 10
Built-in List functions
The Python language has several built-in methods for working with lists. The following table describes the most common method: the Python List method.
Method
Description
append(x)
This method adds elements to the list
pop()
This method removes elements from the list. By default, it removes them from the end of the
list.
count()
This method returns the number of specified values.
remove()
This method removes the element from the list. It removes the first item from the list
reverse()
This method reverses the order of the list
sort()
This method sorts the list
insert()
This method adds the item in the list by specific position
clear()
This method removes all the elements from the list
copy()
copy of the list
Conclusion
In this article, we learned about the list data structure in the Python programming language. This is a mutable data structure in Python, which means we can change the items in the list. There are various approaches to adding items to the list and removing items from the list, which we mentioned in this article. Understanding the list of components is very important for Python developers. You can dive deep into Python by pursuing the Certificate Program in DevOps & Cloud Engineering.
FAQs
What is a list in Python?
A list is a mutable data structure that can store different types of values. It is a built-in type of data structure in the Python programming language.
How to create a list in Python?
We can create a list using brackets, passing the elements within brackets and separating them by commas. For example, [“harry”, 1,].
How to reverse a list in Python?
We can create a reverse list using the inbuilt defined method, the reverse() method. This method reverses the list.
Is a list mutable in Python?
Yes, a List is a mutable data structure in Python, which means we can modify the data
How can I merge two lists?
In Python, we can merge two or most lists using the ‘+’ operators. Another approach, the “extend()” method, is also available.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.