Create nested list in python

Nested Lists in Python

Nested lists are Python representations of two dimensional arrays. They are used to represent lists of lists. For example, a list of grocery lists for the month or matrices we can multiply. In this post we’re going to go over how to use Python to create and manipulate nested lists.

  • Python Nested lists
  • List Comprehension with Nested Lists
  • Adding Lists to a Two Dimensional Array
  • Putting Two Dimensional Lists Together in Python
  • How to Reverse a Nested List
  • Reversing the Sub Elements of a Nested List
  • Reversing the Sub Elements and Elements of a 2D Python Array
  • Turning a 2D List into a Normal List
  • Reverse a Flattened Nested List
  • Summary of Python List within List

Python Nested Lists

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

List Comprehension with Python Nested Lists

We can also create nested lists with list comprehension. List comprehension is a way to create lists out of other lists. In our example below, we’ll create two lists with list comprehension in two ways.

Читайте также:  Division by zero javascript

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)

The results of the two lists should be:

Adding Lists to a Two Dimensional Array

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)

This should result in this list:

Concatenating Two Dimensional Lists in Python

Other than adding a list to our 2D lists, we can also add or concatenate two nested lists together. List concatenation in Python is quite simple, all we need to do is add them with the addition sign. Adding nested lists works the same way as adding plain, unnested lists. In our example, we’ll add the two lists we created using list comprehension together.

# concat nested lists concat_nlist = nlist_comp1 + nlist_comp2 print(concat_nlist)

The list we should see from this is:

How to Reverse a Nested List in Python

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)

This should print out the nested list:

Reversing the Sub Elements of a Nested List

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)

If we call the above code on the original concatenated list, we will see this list:

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

Reverse the Sub Elements and the Elements of a 2D Python Array

Now we can reverse the elements in a 2D list as well as reverse the elements of each nested list, we can put them together. To reverse the sub elements and the elements of a 2D list in Python, all we do is loop through each of the inside lists and reverse them, and then reverse the outside list after the loop. We can also do it in the reverse order.

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

Running this on the original concat_nlist should give:

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

Turning a 2D List into a Normal List

So far, we’ve learned how to create, add to and together, and reverse a two-dimensional list in Python. Now, let’s take a look at turning that 2D list into a normal or flattened list. In this example, we’ll use list comprehension to extract each element from each sublist in the list.

# flatten list flat_list = [ele for sublist in concat_nlist for ele in sublist] print(flat_list)

When running the above code to flatten a list on the original concatenated lists, we should get this list:

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

Reverse a Flattened Nested List Python

Let’s put it all together. We just flattened our 2D Python array into a one-dimensional list. Earlier, we reversed our 2D list. Now, let’s reverse our flattened list. Just like with the 2D list, all we have to do to reverse our flattened list is run the reverse function on the flattened list.

# reverse elements of a flattened list flat_list.reverse() print(flat_list)

After running the reverse function on the list we flattened above, we should get:

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

Summary of Python Nested Lists

In this post about nested lists in Python we learned how to create, manipulate, and flatten nested lists. First we learned how to simply create nested lists by just putting lists into a list, then we learned how to create nested lists through list comprehension.

Next, we learned how to do some manipulation of 2D arrays in Python. First, how to append a list, then how to concatenate two lists, and finally, how to reverse them. Lastly, we learned how to flatten a 2D list and reverse it.

Further Reading

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Источник

Python Nested List

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.

You can use them to arrange data into hierarchical structures.

Create a Nested List

A nested list is created by placing a comma-separated sequence of sublists.

L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']

Access Nested List Items by Index

You can access individual items in a nested list using multiple indexes.

The indexes for the items in a nested list are illustrated as below:

Python Nested List Indexing

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

Negative List Indexing In a Nested List

You can access a nested list by negative indexing as well.

Negative indexes count backward from the end of the list. So, L[-1] refers to the last item, L[-2] is the second-last, and so on.

The negative indexes for the items in a nested list are illustrated as below:

Python Nested List Negative Indexing

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

Change Nested List Item Value

You can change the value of a specific item in a nested list by referring to its index number.

L = ['a', ['bb', 'cc'], 'd'] L[1][1] = 0 print(L) # Prints ['a', ['bb', 0], 'd']

Add items to a Nested list

To add new values to the end of the nested list, use append() method.

L = ['a', ['bb', 'cc'], 'd'] L[1].append('xx') print(L) # Prints ['a', ['bb', 'cc', 'xx'], 'd']

When you want to insert an item at a specific position in a nested list, use insert() method.

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

You can merge one list into another by using extend() method.

L = ['a', ['bb', 'cc'], 'd'] L[1].extend([1,2,3]) print(L) # Prints ['a', ['bb', 'cc', 1, 2, 3], 'd']

Remove items from a Nested List

If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item.

L = ['a', ['bb', 'cc', 'dd'], 'e'] x = L[1].pop(1) print(L) # Prints ['a', ['bb', 'dd'], 'e'] # removed item print(x) # Prints cc

If you don’t need the removed value, use the del statement.

L = ['a', ['bb', 'cc', 'dd'], 'e'] del L[1][1] print(L) # Prints ['a', ['bb', 'dd'], 'e']

If you’re not sure where the item is in the list, use remove() method to delete it by value.

L = ['a', ['bb', 'cc', 'dd'], 'e'] L[1].remove('cc') print(L) # Prints ['a', ['bb', 'dd'], 'e']

Find Nested List Length

You can use the built-in len() function to find how many items a nested sublist has.

L = ['a', ['bb', 'cc'], 'd'] print(len(L)) # Prints 3 print(len(L[1])) # Prints 2

Iterate through a Nested List

To iterate over the items of a nested list, use simple for loop.

L = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] for list in L: for number in list: print(number, end=' ') # Prints 1 2 3 4 5 6 7 8 9

Источник

Оцените статью