Is there any way that i can access the items of nested list ?
# Here a is the nested list
a = [1, 2, [3,4]]
a[0] == 1
a[1] == 2
a[2] == [3,4]
# k is the new list
k = a[2]
k[0] == 3
k[1] == 4
you said without creating a new list
I would like to explain a bit about that for you. By declaring b=a[2] you are definitely not creating a new list. Check this out in your interpreter.
>>> a = [1,2,[3,4]]
>>> b = a[2]
>>> hex(id(a[2]))
'0x7f1432fcd9c8'
>>> hex(id(b))
'0x7f1432fcd9c8'
hex(id(your_variable)) just returns the address of the variable.
'0x7f1432fcd9c8' is the address of a[2] and b. Did you notice how they both are the same?
>>> b=a[:]
>>> hex(id(a))
'0x7f1431850608'
>>> hex(id(b))
'0x7f1432fb9808'
b=a[:] this only creates a fresh copy. Notice how addresses are different.
But look at this one below.
>>> a
[1, 2, [3, 4]]
>>> b=a
>>> hex(id(a))
'0x7f1431850608'
>>> hex(id(b))
'0x7f1431850608'
Same addresses. What does this mean ? It means in Python only the reference (i.e address of memory of the value is assigned to variables. So remember not to forget this. Also
To access elements in your nested loops use subscripts.
>>> a = [1,2,[3,4],[[9,9],[8,8]]]
>>> a[1]
2
>>> a[2]
[3, 4]
>>> a[2][0]
3
>>> a[3][1]
[8, 8]
>>> a[3][1][0]
8
Accessing elements this way is done in O(1) time so it is the fastest way possibile.
As you concern seem to be that you are making a new list: stop worrying you are not.
After
k = a[2]
both k and a[2] refer to the same list. Nothing new is created.
You can easily verify that by changing k[0] to something different than the element 3 it already has in that position:
k[0] = 5
and then
print(a)
which gives
[1, 2, [5, 4]]
If you wanted to create a new list you would have to explicitly do something like:
k = a[2][:]
[3, 4]part of your list? It is at position "2" of your list, soa[2]will get you that part of the list. If you need to access the elements of the list from there then:a[2][0]will get you the first, anda[2][1]will get you the second.