Besides Swift we have already mentioned in the previous blog, Python is also one of the programming languages for developers. When coming to this kind of programming language, users have lots of awesome functions to explore. So in this article, ArrowHiTech will give you more information about *List of lists python: The comprehensive guide for you. *However, don’t worry if you don’t have any idea about it. Because we will start now.

## What is a List of lists python?

Firstly, list of lists python is the list object with each list element being a separate list. Furthermore, in Python, you should make a nested list by using the square bracket notation

For example: [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

## Memory Analysis

Firstly, it’s necessary to remember that a list is a collection of memory references. So you’ll obtain a better knowledge of how Python works at its core by experimenting with the code visualizer:

## How to create a list of lists python?

Using the square bracket notation, so you can make a list of lists python.

*For example:* Use [[1, 2], [3, 4]] to make list of lists python of integer values. Therefore, the outer python list of lists elements are all nested lists.

## How to convert list of lists python?

### #1 Convert list of lists python to One List

In case you want to combine a collection of lists [[1, 2], [3, 4]] into a [1, 2, 3, 4]. So what is the best way to accomplish this? We have several choices for you:

- Firstly, if you have a List of Lists in Python, you may use list comprehension [x for l in lst for x in l].
- Secondly, assuming you have a list of two lists lst, unpacking [*lst[0], *lst[1]].
- Finally, to expand all lists in a list of lists, use the extend() method of Python lists.

The following code snippet has examples of all three ways:

lst = [[1, 2], [3, 4]]

#### # Method 1: Comprehensive list python

flat_1 = [x for l in lst for x in l]

#### # Method 2: Unpacking

flat_2 = [*lst[0], *lst[1]]

#### # Method 3: Extend Method

flat_3 = []

for l in lst:

flat_3.extend(l)

## Check results:

print(flat_1)

# [1, 2, 3, 4]

print(flat_2)

# [1, 2, 3, 4]

print(flat_3)

# [1, 2, 3, 4]

The first comprehensive list python approach is superior to the other two approaches due to its simplicity and efficiency.

### #2 Convert list of lists python to Dictionary

Firstly, converting a list of lists into a dictionary might be very helpful in some cases. In Python, there are three basic methods for converting a list of lists into a dictionary (source): For Loop, Dictionary Comprehension, Generator Expression

Thus, let’s take a look at each one right now

**For example: **

You have a list of lists, each of which represents a person and has three values for the individual’s name, age, and hair color. Moreover, you want to make a dictionary that uses a person’s name as the dictionary key and a sublist of age and hair color as the dictionary value for convenience.

*For Loop*

.A regular for loop can also be used to define the dictionary elements one by one within a simple for loop. Therefore, the alternate code is as follows:

persons = [[‘Alice’, 25, ‘blonde’],

[‘Bob’, 33, ‘black’],

[‘Ann’, 18, ‘purple’]]

persons_dict = {}

for x in persons:

persons_dict[x[0]] = x[1:]

print(persons_dict)

# {‘Alice’: [25, ‘blonde’],

# ‘Bob’: [33, ‘black’],

# ‘Ann’: [18, ‘purple’]}

*Dictionary Comprehension*

This may be accomplished by using Python’s dictionary comprehension functionality.

persons = [[‘Alice’, 25, ‘blonde’],

[‘Bob’, 33, ‘black’],

[‘Ann’, 18, ‘purple’]]

persons_dict = {x[0]: x[1:] for x in persons}

print(persons_dict)

# {‘Alice’: [25, ‘blonde’],

# ‘Bob’: [33, ‘black’],

# ‘Ann’: [18, ‘purple’]}

Therefore, the x[0]: x[1:] expression in the dictionary comprehension statement assigns a person’s name x[0] to the list x[1:] containing the person’s age and hair color. It also includes the context for x in individuals, which iterates across all “data rows.”

*Generator Expression*

Using a generator expression in combination with the dict() constructor to produce the dictionary is a comparable approach of accomplishing the same thing.

persons = [[‘Alice’, 25, ‘blonde’],

[‘Bob’, 33, ‘black’],

[‘Ann’, 18, ‘purple’]]

persons_dict = dict((x[0], x[1:]) for x in persons)

print(persons_dict)

# {‘Alice’: [25, ‘blonde’],

# ‘Bob’: [33, ‘black’],

# ‘Ann’: [18, ‘purple’]}

So this line of code is nearly identical to the one used in the “list comprehension” section. The main difference is that you fill the dictionary with tuples rather than direct mappings.

### #3 Convert list of lists python to NumPy Array

In Python, you’re given a list of lists. What’s the best way to turn it into a 2D NumPy array?

**For example:**

Convert the following list of lists

Into a NumPy array

*Solution:*

So in order to transform a list of lists into a two-dimensional NumPy array, use the np.array(list) method. Moreover, the code is as follows:

# Import the NumPy library

import numpy as np

# Create the list of lists

lst = [[1, 2, 3], [4, 5, 6]]

# Convert it to a NumPy array

a = np.array(lst)

# Print the resulting array

print(a)

”’

[[1 2 3]

[4 5 6]]

*Convert a list of lists python With Different Number of Elements*

Given a list of lists. So please solve the problem. The amount of elements in the inner lists varies. Thus, what’s the best way to turn them into a NumPy array?

**For example:**

You’ve got a list of lists like this:

So what are the various methods for converting this collection of lists into a NumPy array?

*Solution:*

There are three different strategies you can use

##### Use the standard *np.array()* function.

# Import the NumPy library

import numpy as np

# Create the list of lists

lst = [[1, 2, 3], [4, 5], [6, 7, 8]]

# Convert it to a NumPy array

a = np.array(lst)

# Print the resulting array

print(a)

”’

[list([1, 2, 3]) list([4, 5]) list([6, 7, 8])]

This produces a three-element NumPy array, each of which is a list type. The built-in type() function can be used to determine the output type:

>>> type(a)

<class ‘numpy.ndarray’>

##### Make an array of arrays.

# Import the NumPy library

import numpy as np

# Create the list of lists

lst = [[1, 2, 3], [4, 5], [6, 7, 8]]

# Convert it to a NumPy array

a = np.array([np.array(x) for x in lst])

# Print the resulting array

print(a)

”’

[array([1, 2, 3]) array([4, 5]) array([6, 7, 8])]

##### Make the lists equal in length.

# Import the NumPy library

import numpy as np

# Create the list of lists

lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

# Calculate length of maximal list

n = len(max(lst, key=len))

# Make the lists equal in length

lst_2 = [x + [None]*(n-len(x)) for x in lst]

print(lst_2)

# [[1, 2, 3, None], [4, 5, None, None], [6, 7, 8, 9]]

# Convert it to a NumPy array

a = np.array(lst_2)

# Print the resulting array

print(a)

”’

[[1 2 3 None]

[4 5 None None]

[6 7 8 9]]

### #4 Convert List of Lists to List of Tuples

*Method 1: List Comprehension + tuple()*

**For example:**

You’ve got a list of lists [[1, 2], [3, 4], [5, 6]] that you want to convert into a list of tuples [(1, 2), (3, 4), (5, 6)].

*Solution: *

lst = [[1, 2], [3, 4], [5, 6]]

tuples = [tuple(x) for x in lst]

print(tuples)

# [(1, 2), (3, 4), (5, 6)]

Therefore, this strategy is both simple and effective. List comprehension specifies how each value (in this case, x) is converted into a new list element. You use the constructor tuple(x) to build a new tuple from the list x because each list element is a new tuple.

Additionally, if the number of list entries in each sublist varies, this method still works well:

lst = [[1], [2, 3, 4], [5, 6, 7, 8]]

tuples = [tuple(x) for x in lst]

print(tuples)

# [(1,), (2, 3, 4), (5, 6, 7, 8)]

*Method 2: Map Function + tuple()*

Without further ado, here’s how you use the map() method to transform a list of lists into a list of tuples:

lst = [[1], [2, 3, 4], [5, 6, 7, 8]]

tuples = list(map(tuple, lst))

print(tuples)

# [(1,), (2, 3, 4), (5, 6, 7, 8)]

The name of the tuple function is the first input to the map() method. The tuple() function creates a tuple from each member of the iterable lst (the second argument). Due to the map() function returns an iterable, you must convert it to a list before displaying it to the shell. Because an iterable’s default string representation is not human-readable.

### #5 Convert list of lists python to CSV File

**For example: **

A list of lists is given. For example, wage data for employees in a specific company:

So this is what your outfile should look like:

*Method 1: Python’s CSV Module*

Using the csv library, you can simply convert a list of lists to a CSV file in Python. Therefore, this approach is the most flexible of the four.

salary = [[‘Alice’, ‘Data Scientist’, 122000],

[‘Bob’, ‘Engineer’, 77000],

[‘Ann’, ‘Manager’, 119000]]

# Method 1

import csv

with open(‘file.csv’, ‘w’, newline=”) as f:

writer = csv.writer(f)

writer.writerows(salary)

*Output:*

*Method 2: Pandas DataFrame to_csv()*

Firstly, a list of lists can be converted to a Pandas DataFrame. It has powerful features like the to csv() method. This is the simplest option, and it avoids the trouble of having to import yet another library.

salary = [[‘Alice’, ‘Data Scientist’, 122000],

[‘Bob’, ‘Engineer’, 77000],

[‘Ann’, ‘Manager’, 119000]]

# Method 2

import pandas as pd

df = pd.DataFrame(salary)

df.to_csv(‘file2.csv’, index=False, header=False)

*Output:*

*Method 3: NumPy savetext()*

Firstly, NumPy provides the foundation for Python’s data science and machine learning capabilities. Therefore, NumPy arrays are used by Pandas to implement critical functionality.

If you simply have numerical data, this method is optimal. Moreover, it will result in complicated data type conversions, which are not advised.

a = [[1, 2, 3],

[4, 5, 6],

[7, 8, 9]]

# Method 3

import numpy as np

a = np.array(a)

np.savetxt(‘file3.csv’, a, delimiter=’,’)

*Output:*

*Method 4: Pure Python Without External Dependencies*

In case you don’t want or can’t use external dependencies. So this is the approach to utilize.

salary = [[‘Alice’, ‘Data Scientist’, 122000],

[‘Bob’, ‘Engineer’, 77000],

[‘Ann’, ‘Manager’, 119000]]

# Method 4

with open(‘file4.csv’,’w’) as f:

for row in salary:

for x in row:

f.write(str(x) + ‘,’)

f.write(‘\n’)

*Output:*

## What is a List of lists python functions?

### #1 Remove Empty

You have a list of lists. [[1, 2, 3], [1, 2], [], [], [], [1, 2, 3, 4], [], []]. Besides that, you want all empty lists removed to obtain the list of lists [[1, 2, 3], [1, 2], [1, 2, 3, 4]]. So how do you eliminate all the empty lists in a list of lists?

Solution:

1st = [[1, 2, 3], [1, 2], [], [], [], [1, 2, 3, 4], [], []]

print([x for x in lst if x])

# [[1, 2, 3], [1, 2], [1, 2, 3, 4]]

### #2 Remove Duplicates

*Method 1: Naive Method*

lst = [[1, 1], [0, 1], [0, 1], [1, 1]]

dup_free = []

for x in lst:

if x not in dup_free:

dup_free.append(x)

print(dup_free)

# [[1, 1], [0, 1]]

*Method 2: Temporary Dictionary Conversion*

lst = [[1, 1], [0, 1], [0, 1], [1, 1]]

# 1. Convert into list of tuples

tpls = [tuple(x) for x in lst]

# 2. Create dictionary with empty values and

# 3. convert back to a list (dups removed)

dct = list(dict.fromkeys(tpls))

# 4. Convert list of tuples to list of lists

dup_free = [list(x) for x in lst]

# Print everything

print(dup_free)

# [[1, 1], [0, 1], [0, 1], [1, 1]]

*Method 3: Set Conversion*

lst = list(range(10)) + list(range(10))

lst = list(set(lst))

print(lst)

# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Does this also work for tuples? Yes!

lst = [(10,5), (10,5), (5,10), (3,2), (3, 4)]

lst = list(set(lst))

print(lst)

# [(3, 4), (10, 5), (5, 10), (3, 2)]

### #3 Reverse

This is the *list.reverse()* function that reverses the order of the list’s elements. Therefore, you should use slicing with negative step size *list[::-1]* to produce a new list with reversed elements.

*Flat Reverse*

Using the list.reverse() function on a list of lists. However, you only get a “flat” reverse—just the outer list is reversed, not the inside ones. Thus, you should use slicing with negative step size list[::-1] to make a new list with reversed elements.

lst = [[1, 2], [1, 2, 3, 4]]

lst.reverse()

print(lst)

# [[1, 2, 3, 4], [1, 2]]

*Deep Reverse*

def deep_reverse(lst):

”’ Reverses a nested list in place”’

# Reverse top-level list

lst.reverse()

# Recursively reverse all nested lists

for element in lst:

if isinstance(element, list):

deep_reverse(element)

lst = [[1, 2], [1, 2, 3, 4]]

deep_reverse(lst)

print(lst)

# [[4, 3, 2, 1], [2, 1]]

Therefore, the second-level list, as well as the first-level list, has been reversed.

**#4 Zip **

Firstly, by merging the i-th values of each iterable into a tuple, the zip() function combines a number of iterables into a single one.

For example: zip lists [1, 2, 3] and [4, 5, 6] together to get [(1,4), (2,5), (3,6)].

*Problem:* The zip function requires an arbitrary amount of iterables, therefore passing a list of lists to it won’t work (and not iterable of iterables).

*For example: *

You want to zip a list of lists:

*Solution: *

So using the “unpacking” asterisk operator, unpack the lists in the list of lists.

>>> list(zip(*[[1, 2], [3, 4], [5, 6]]))

[(1, 3, 5), (2, 4, 6)]

### #5 Unpack

A list of lists is only one iterable, but the zip function requires several iterables. Therefore, to fix this problem, you use the zip function to unpack the inner lists and use them as arguments for the iterables. In addition, Zip() takes three iterable inputs in this case: [1, 2], [3, 4], and [5, 6].

### #6 Average

*Problem:*** **

You have a list of lists and want to average the values in each column.

*For example: *

Given the following list of lists with four rows and three columns.

Furthermore, the average values of the three columns are what you’re looking for:

*Method 1: Average in Python (No Library)*

In Python, a simple one-liner using list comprehension and the zip() function on the unpacked list to transpose the list of lists accomplishes the task.

data = [[0, 1, 0],

[1, 1, 1],

[0, 0, 0],

[1, 1, 0]]

# Method 1: Pure Python

res = [sum(x) / len(x) for x in zip(*data)]

print(res)

# [0.5, 0.75, 0.25]

*Method 2: Average with NumPy Library*

The data is converted into a NumPy array and passed to the np.average() function.

data = [[0, 1, 0],

[1, 1, 1],

[0, 0, 0],

[1, 1, 0]]

# Method 2: NumPy

import numpy as np

a = np.array(data)

res = np.average(a, axis=0)

print(res)

# [0.5 0.75 0.25]

*Method 3: Mean Statistics Library + Map()*

To demonstrate another option, here’s one that uses the map() function and our zip(*data) method to transpose the “matrix” data.

data = [[0, 1, 0],

[1, 1, 1],

[0, 0, 0],

[1, 1, 0]]

# Method 3: Statistics + Map()

import statistics

res = map(statistics.mean, zip(*data))

print(list(res))

# [0.5, 0.75, 0.25]

### #7 Sum

So now let’s make sure we’re on the same page. Because here’s a visual representation of your to-do list and what you intend to accomplish:

*For example:*

### #8 Copy

*Flat Copy*

Before you can fully understand the Python copy() method, you must first know the concept of a “shallow copy” or “flat copy.”

Everything is an object in object-oriented languages like Python. The list is an object, and the list’s elements are also objects. A shallow copy of the list creates a new list object (the copy), but not new list elements, instead copying the references to these objects.

*For example:*

lst = [[1, 0], [2, 2], [0, 0]]

lst_copy = lst.copy()

lst_copy[2].append(42)

print(lst[2])

Output:

*Deep Copy*

After you’ve known the concept of a shallow copy, it’ll be simple to understand the concept of a deep copy. A shallow copy just copies the list elements’ references. Because the list elements may be lists that need to be copied deeply, a deep copy can result in a highly recursive behavior.

*For example:*

import copy

lst = [[1, 0], [2, 2], [0, 0]]

lst_copy = copy.deepcopy(lst)

lst_copy[2].append(42)

print(lst[2])

# [0, 0]

### #9 Group By

*Input:*

# Database:

# row = [Name, Age, Income]

rows = [[‘Alice’, 19, 45000],

[‘Bob’, 18, 22000],

[‘Ann’, 26, 88000],

[‘Alice’, 33, 118000]]

# Create a dictionary grouped by Name

d = {}

for row in rows:

# Add name to dict if not exists

if row[0] not in d:

d[row[0]] = []

# Add all non-Name attributes as a new list

d[row[0]].append(row[1:])

print(d)

# {‘Alice’: [[19, 45000], [33, 118000]],

# ‘Bob’: [[18, 22000]],

# ‘Ann’: [[26, 88000]]}

## How to Filter a list of lists python?

Use the list comprehension statement [x for x in list if condition(x)] to filter a list of lists python for a condition on the inner lists. Replace condition(x) with your filtering condition that returns True if inner list x is included, and False otherwise.

*For example: *

Given the following list of weekly temperature measurements for each week and one inner list for each week.

So how can I select out the weeks with an average temperature of -8? This is the result you’re looking for:

List comprehension and the map() function are two semantically equivalent approaches for accomplishing this. Therefore, we’ll look at both options:

# Measurements of a temperature sensor (7 per week)

temperature = [[10, 8, 9, 12, 13, 7, 8], # week 1

[9, 9, 5, 6, 6, 9, 11], # week 2

[10, 8, 8, 5, 6, 3, 1]] # week 3

# How to filter weeks with average temperature <8?

#### Method 1: List Comprehension

cold_weeks = [x for x in temperature if sum(x)/len(x)<8]

print(cold_weeks)

# [[9, 9, 5, 6, 6, 9, 11], [10, 8, 8, 5, 6, 3, 1]]

#### Method 2: Map()

cold_weeks = list(filter(lambda x: sum(x) / len(x) < 8, temperature))

print(cold_weeks)

# [[9, 9, 5, 6, 6, 9, 11], [10, 8, 8, 5, 6, 3, 1]]

## Conclusion

As you can see, above is all about List of lists python that ArrowHiTech wants to provide to you. However, if you are not clear about it. So don’t hesitate. Feel free to contact us at **HERE**. We are experienced professionals in the field of ECommerce, Web/mobile apps, CMS website development as well as Salesforce and Software Consultant & Development.