The list is one of the built-in data types in python. Lists are versatile and flexible data types that can store one or more objects or values. Unlike tuples, lists are mutable and can be manipulated. List literals in python are written within square brackets.
Table of Contents
Each element within the list is called an item and items are separated by commas. A list can have any number of items and the items can be of different data types (integer, float, strings, etc.).
Lists in python are similar to string data types and functions like len() can be applied to lists. Furthermore, each item has a specific index, and the index operator [] can be used to access a specific item in a list.
my_list = [2, "List", "in", "Python", 5.00]
print(type(my_list))
print(my_list[3])
print(my_list)
Output:
Combining two lists
In python, different methods can be used to combine two lists. The easiest method is by using the ‘+’ operator. In this method, the contents of both lists are concatenated, and the output is stored in another list.
list1 = ["Python", 1, 4.00]
list2 = ["Lists", 2, 7.89]
# Combining two lists using the '+' operator
list3 = list1 + list2
# Printing new list
print(list3)
Output:
Using list comprehension
The method of list comprehension can also be used for list concatenation. This method is a shorter and alternative method to the loop method. This method relies on the usage of a list comprehension to loop over a given list and then append it to another list.
list1 = ["Python", 1, 4.00]
list2 = ["Lists", 2, 7.89]
# Using list comprehension
list3 = [x for y in (list1, list2) for x in y]
# Printing the concatenated list
print(list3)
Output:
Using the extend() method
In extend() method, all the elements of an iterable (list, tuple, string, etc.) are added to the end of the list. It extends the second list to the end of the first list. It also updates the original list directly. Furthermore, this method retains the order of list elements and also contains duplicate elements.
list1 = ["Python", 1, 4.00]
list2 = ["Lists", 2, 7.89]
# Using extend() to concatenate the lists
list1.extend(list2)
# Printing the concatenated list
print(list1)
Output:
Using unpacking * operator
The * operator method is a relatively new method of list concatenation and works only on Python 3.6+. An asterisk * denotes iterable unpacking.
The * operator is used to concatenate the list while maintaining the order of the elements. The * operators first unpack the content of the data types and then create a list from the content.
list1 = ["Python", 1, 4.00]
list2 = ["Lists", 2, 7.89]
# Merging the lists using the unpacking operator
list3 = [*list1, *list2]
# Printing the concatenated list
print(list3)
Output:
Using itertools.chain()
In this method, itertools module is used to concatenate the lists. itertools.chain() method takes the arguments in the form of lists and returns a single sequence of items. So, the chain() method concatenates all the available lists.
The result of the method call is converted into a list using the list() method.
# Importing the itertools module
import itertools
list1 = ["Python", 1, 4.00]
list2 = ["Lists", 2, 7.89]
# Concatenate using the itertools
list3 = list(itertools.chain(list1, list2))
# Printing the concatenated list
print(list3)
Output:
=> Join the Waitlist for Early Access.
Comparing two lists in Python
There are different ways of comparing lists in python but often it depends on the outcome required.
Using the “==” operator
The easiest way of comparing lists in python is using the ‘==’ operator. It works for simple cases but may find limitations when dealing with floating points and some complex comparison operations.
The list in python is sensitive to the order, so even if the list has the same content but the order is not the same, then it will show they are not equal. To tackle this issue, lists can be first sorted, and then the ‘==’ operator can be applied.
list1 = ["python", 4, 7]
list2 = [4, 7, "python"]
list3 = ["python", 4, 7]
list4 = ["python", 4, 7]
print(list1 == list2)
print(list3 == list4)
Output:
Using sets in Python
In this method, the set() method is used to compare lists. Firstly, lists are passed as an argument to the set method. Secondly, the resulting sets are then compared using the ‘==’ operator.
list1 = ["python", 4, 7.0]
list2 = [4, 7, "python"]
x = set(list1)
y = set(list2)
print(x == y)
Output:
Using collections library
In this method, the collection library is used to compare lists efficiently. The counter() of this method counts the occurrence of items in the list and stores the data in dictionary format. If the dictionary output of given lists is the same, then we can infer that the lists are the same.
import collections
list1 = ["python", 4, 7.0]
list2 = [4, 7, "python"]
if collections.Counter(list1) == collections.Counter(list2):
print ("The two lists are the same")
else:
print ("The two lists are not the same")
Output:
List of lists in Python
In python, we can also have lists within lists called nested lists or two-dimensional lists. We can use different ways to create a list of lists in Python.
Using the append() method
In this method, an empty list is created initially. After creating the empty list, the append() method is used to append all the given lists to create a new list. The append() method adds the given lists to the end of the list.
list1 = ["python", 4]
list2 = [7, "lists"]
list3 = ["Append", 8]
new_list = []
new_list.append(list1)
new_list.append(list2)
new_list.append(list3)
print(new_list)
Output:
Using the comprehension method
In this method, for loop along with a conditional statement within the square bracket is used to create the lists of lists in python. This method is concise and pretty straightforward.
list1 = ["python", 4, 7.0]
list = [list1 for i in range(3)]
print(list)
Output:
Using for-loop
In this method, nested loops are used to create a list of lists. This method explicitly uses the append() method along with for loop for the creation of a list of lists.
list = []
for i in range(3):
list.append([])
for j in range(3):
list[i].append(j)
print(list)
Output:
Flatten list of lists
Flattening lists in python is converting a nested or two-dimensional list into a normal single list. Many approaches can be used to convert the nested list into normal lists.
Using list comprehension
The method of nested list comprehension can be used to flatten a nested list.
list = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
flatten_list = [i for row in list for i in row]
print(flatten_list)
Output:
Using nested loops
This is the most intuitive and at the same time brute force approach for flattening the nested list. In this method, each element from the nested lists is appended to the flattened list.
list = [["a","b","c"],["d","e","f"],["g","h","i"]]
flatten_list = []
for i in range(len(list)):
for j in range (len(list[i])):
flatten_list.append(list[i][j])
print(flatten_list)
Output:
Using numpy
In this method, the numpy library is used to flatten the nested lists. The concatenate() method of the numpy library is used to concatenate the nested list either row-wise or column-wise. Furthermore, the flat attribute is used over the given array to flatten the nested list.
import numpy
List = [["a","b","c"],["d","e","f"],["g","h","i"]]
flatten_list = list(numpy.concatenate(List).flat)
print(flatten_list)
Output:
Tanner Abraham
Data Scientist and Software Engineer with a focus on experimental projects in new budding technologies that incorporate machine learning and quantum computing into web applications.=> Join the Waitlist for Early Access.