0

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
1
  • What exactly are you looking to do? Are you just trying to access the [3, 4] part of your list? It is at position "2" of your list, so a[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, and a[2][1] will get you the second. Commented Jun 24, 2017 at 3:54

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can access it by providing two subscripts, like this:

a = [1, 2, [3,4]]
a[2][0] == 3
a[2][1] == 4

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.