Ways to write nested lists in python matter?

Hello, I have a simple question. Is it the same to write a nested list like this:

Nest1=[1,2,[3,4,[‘a’,‘b’]]]

Nest2=[[1,2],[3,4],[‘a’,‘b’]]

If this makes a change, what is the difference?

Thank you

Hi @Maria_Dorland

Thank You for reaching out to the Educative team.

Nest1 and Nest2 are not same. Let me break down the structures for you:

  • Nest1=[1,2,[3,4,[‘a’,‘b’]]]
    Nest1 in this case is a list with three entries. The list [3, 4, ['a', 'b']] that makes up the third element is nested inside the outer list. This produces three layers of nesting in a hierarchical structure. Let’s see this visually
   Nest1
    |
  __|__
 |  |  |
 1  2   __|__
        |   |
        3   4
          |
        __|__
       |     |
      'a'   'b'

You can access the following above elements of Nest1 as follows:

Nest1[0] => 1
Nest1[1] => 2

nested_list = Nest1[2] // This means [3, 4, ['a', 'b']]

nested_list[0] => 3
nested_list[1] => 4

nested_list_2 = nested_list[2] // This means ['a', 'b']

nested_list_2[0] => a
nested_list_2[1] => b
  • Nest2=[[1,2],[3,4],[‘a’,‘b’]]
    You have a list of lists in Nest2. In the outer list, every inner list—[1, 2], [3, 4], and ['a', 'b']—is a distinct element. Similar to Nest1, this construction contains three layers of nesting, but the nesting is more consistent. Let’s see this visually
      Nest2
  ______|_______
  |     |       |
  |     |       |
[1, 2] [3, 4]  ['a', 'b']

You can access the following above elements of Nest2 as follows:

Nest2[0][0] => 1
Nest2[0][1] => 2

Nest2[1][0] => 3
Nest2[1][1] => 4

Nest2[2][0] => a
Nest2[2][1] => b

I hope it helps. Happy Learning :blush:

1 Like