 # python nested lists and arrays

• Last Update :
• Techknowledgy :

Last Updated : 09 Jul, 2021,GATE CS 2021 Syllabus

Output :

[
[1, 7, 0],
[6, 2, 5]
]
[
[1 7 0]
[6 2 5]
]

Suggestion : 2

The easiest way to create a nested list in Python is simply to create a list and put one or more lists in that list. In the example below we’ll create two nested lists. First, we’ll create a nested list by putting an empty list inside of another list. Then, we’ll create another nested list by putting two non-empty lists inside a list, separated by a comma as we would with regular list elements.

# create a nested list
nlist1 = [
[]
]
nlist2 = [
[1, 2],
[3, 4, 5]
]

First we’ll create a nested list using three separate list comprehensions. Second, we’ll create a nested list with nested list comprehension.

# create a list with list comprehension
nlist_comp1 = [
[i
for i in range(5)
],
[i
for i in range(7)
],
[i
for i in range(3)
]
]
nlist_comp2 = [
[i
for i in range(n)
]
for n in range(3)
]
print(nlist_comp1)
print(nlist_comp2)

Now that we’ve learned how to create nested lists in Python, let’s take a look at how to add lists to them. We work with nested lists the same way we work with regular lists. We can add an element to a nested list with the append() function. In our example, we create a list and append it to one of our existing lists from above.

# append a list
list1 = [8, 7, 6]
nlist_comp1.append(list1)
print(nlist_comp1)

Now that we’ve created, added to, and concatenated nested lists, let’s reverse them. There are multiple ways to reverse nested lists, including creating a reversed copy or using list comprehension. In this example though, we’ll reverse a list in place using the built-in reverse() function.

# reverse a nested list
concat_nlist.reverse()
print(concat_nlist)

Okay, so we can easily reverse a list using the reverse function. What if we want to reverse the sub elements of a nested list? We can reverse each of the lists in a nested list by looping through each list in the nested list and calling the reverse function on it.

# reverse sub elements of nested list
for _list in concat_nlist:
_list.reverse()
print(concat_nlist)

Suggestion : 3

The negative indexes for the items in a nested list are illustrated as below:,A list can contain any sort object, even another list (sublist), which in turn can contain sublists themselves, and so on. This is known as nested list.,A nested list is created by placing a comma-separated sequence of sublists.,You can access individual items in a nested list using multiple indexes.

L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L)
# Prints['cc', 'dd', ['eee', 'fff']]

print(L)
# Prints['eee', 'fff']

print(L)
# Prints eee
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L[-3])
# Prints['cc', 'dd', ['eee', 'fff']]

print(L[-3][-1])
# Prints['eee', 'fff']

print(L[-3][-1][-2])
# Prints eee
L = ['a', ['bb', 'cc'], 'd']
L = 0
print(L)
# Prints['a', ['bb', 0], 'd']
L = ['a', ['bb', 'cc'], 'd']
L.append('xx')
print(L)
# Prints['a', ['bb', 'cc', 'xx'], 'd']
L = ['a', ['bb', 'cc'], 'd']
L.insert(0, 'xx')
print(L)
# Prints['a', ['xx', 'bb', 'cc'], 'd']

Suggestion : 4

Lists are useful data structures commonly used in Python programming. A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.,Creating a matrix is one of the most useful applications of nested lists. This is done by creating a nested list that only has other lists of equal length as elements.,The length of the lists inside the nested list is equal to the number of columns.,Thus, each element of the nested list (matrix) will have two indices: the row and the column.

# creating list
nestedList = [1, 2, ['a', 1], 3]

# indexing list: the sublist has now been accessed
subList = nestedList

# access the first element inside the inner list:
element = nestedList

print("List inside the nested list: ", subList)
print("First element of the sublist: ", element)
# create matrix of size 4 x 3
matrix = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11]
]

rows = len(matrix) # no of rows is no of sublists i.e.len of list
cols = len(matrix) # no of cols is len of sublist

# printing matrix
print("matrix: ")
for i in range(0, rows):
print(matrix[i])

# accessing the element on row 2 and column 1 i.e.3
print("element on row 2 and column 1: ", matrix)

# accessing the element on row 3 and column 2 i.e.7
print("element on row 3 and column 2: ", matrix)

Suggestion : 5

Solution: Use the np.array(list) function to convert a list of lists into a two-dimensional NumPy array. ,What are the different approaches to convert this list of lists into a NumPy array?,For some applications, it’s quite useful to convert a list of lists into a dictionary. ,You can convert a list of lists to a CSV file by using NumPy’s savetext() function and passing the NumPy array as an argument that arises from conversion of the list of lists.

For example, to create a list of lists of integer values, use [[1, 2], [3, 4]]. Each list element of the outer list is a nested list itself.

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

Find examples of all three methods in the following code snippet:

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

# Method 1: List Comprehension
flat_1 = [x
for l in lst
for x in l
]

# Method 2: Unpacking
flat_2 = [ * lst, * lst]

# 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]

Solution: You can achieve this by using the beautiful (but, surprisingly, little-known) feature of dictionary comprehension in Python.

persons = [
['Alice', 25, 'blonde'],
['Bob', 33, 'black'],
['Ann', 18, 'purple']
]

persons_dict = {
x: x[1: ]
for x in persons
}
print(persons_dict)
# {
'Alice': [25, 'blonde'],
# 'Bob': [33, 'black'],
# 'Ann': [18, 'purple']
}

Here’s the alternative code:

persons = [
['Alice', 25, 'blonde'],
['Bob', 33, 'black'],
['Ann', 18, 'purple']
]

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

print(persons_dict)
# {
'Alice': [25, 'blonde'],
# 'Bob': [33, 'black'],
# 'Ann': [18, 'purple']
}

Example: Convert the following list of lists

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

Suggestion : 6

Posted on October 28, 2017 by Joseph Santarcangelo

import nunpy as np

u = np.array([1, 0])

v = np.array([0, 1])

Suggestion : 7

For this we have created a recursive function that will use the recursion to go inside this nested list and calculate the total number of elements in it i.e. ,Iterate over the list of lists using List comprehension. Build a new list of sizes of internal lists. Then pass the list to sum() to get total number of elements in list of lists i.e. ,So, in our case we passed the list object to the len() function. Which internally called the __len__() of the list object, to fetch the count of elements in list.,When len(s) function is called, it internally calls the __len__() function of the passed object s. Default sequential containers like list, tuple & string has implementation of __len__() function, that returns the count of elements in that sequence.

Suppose we have a list i.e.

# List of strings
listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']

Python provides a inbuilt function to get the size of a sequence i.e.

len(s)

Now let’s use this len() function to get the size of a list i.e.

listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']

# Get size of a list using len()
length = len(listOfElems)

print('Number of elements in list : ', length)

We can directly call the __len__() member function of list to get the size of list i.e.

listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']

# Get size of a list using list.__len__()
length = listOfElems.__len__()

print('Number of elements in list : ', length)

Suppose we have a list of list i.e.

# List of lists
listOfElems2D = [
[1, 2, 3, 45, 6, 7],
[22, 33, 44, 55],
[11, 13, 14, 15]
]

Suggestion : 8

Suppose that two numbers are given: the number of rows of n and the number of columns m. You must create a list of size n×m, filled with, say, zeros. ,But the easiest way is to use generator, creating a list of n elements, each of which is a list of m zeros:,You can use nested generators to create two-dimensional arrays, placing the generator of the list which is a string, inside the generator of all the strings. Recall that you can create a list of n rows and m columns using the generator (which creates a list of n elements, where each element is a list of m zeros): ,This is how you can use 2 nested loops to calculate the sum of all the numbers in the 2-dimensional list:

1._
None
None
a = [
[1, 2, 3],
[4, 5, 6]
]
print(a)
print(a)
b = a
print(b)
print(a)
a = 7
print(a)
print(b)
b = 9
print(a)
print(b)
1._
None
None
a = [
[1, 2, 3, 4],
[5, 6],
[7, 8, 9]
]
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end = ' ')
print()
1._
None
None
a = [
[1, 2, 3, 4],
[5, 6],
[7, 8, 9]
]
for row in a:
for elem in row:
print(elem, end = ' ')
print()
1._
None
None
a = [
[1, 2, 3],
[4, 5, 6]
]
print(a)
print(a)
b = a
print(b)
print(a)
a = 7
print(a)
print(b)
b = 9
print(a)
print(b)
3._
None

Naturally, to output a single line you can use method join():

for row in a:
print(' '.join([str(elem) for elem in row]))
8._
None
1._
None
None
a = [
[1, 2, 3, 4],
[5, 6],
[7, 8, 9]
]
s = 0
for i in range(len(a)):
for j in range(len(a[i])):
s += a[i][j]
print(s)
1._
None
None
a = [
[1, 2, 3, 4],
[5, 6],
[7, 8, 9]
]
s = 0
for row in a:
for elem in row:
s += elem
print(s)