How To Access The Nested List Items In Python With Out Creating A New List?
Solution 1:
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.
Solution 2:
You can access it by providing two subscripts, like this:
a = [1, 2, [3,4]]
a[2][0] == 3
a[2][1] == 4
Solution 3:
Lists in python are indexed from 0, not 1.
Do this instead.
# 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 can also access the nested list by using the following syntax:
a[2][0] # => 3
a[2][1] # => 2
Solution 4:
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][:]
Post a Comment for "How To Access The Nested List Items In Python With Out Creating A New List?"