1

I'm doing a lab for a basic programming class in Python, and I can't figure out how to return a number in a list, in another list.
I'm supposed to return 4 with "one expression and no parenthesis"

[1,[2,[3,4]]]

Any ideas? All I've gotten so far is returning [2,[3,4]] and I haven't been able to figure out anything past that.

2
  • Don't forget to check the best answer to your question Commented Sep 28, 2011 at 14:26
  • The only way to "return 4" with "one expression and no parentheses" that I can think of is this statement: return 4 Commented Sep 28, 2011 at 15:33

3 Answers 3

7
>>> a = [1,[2,[3,4]]]
>>> a[1]
[2, [3, 4]]
>>> a[1][1]
[3, 4]
>>> a[1][1][1]
4
>>> 
Sign up to request clarification or add additional context in comments.

Comments

2

One expression:

>>> [1,[2,[3,4]]][1][1][1]
4

Comments

2

In case you don't know, to access the last element of a list you can use negative index. a[-1] means the first element from the end. It's very useful when you want to print elements with position relative to the end.

>>> a = [1,[2,[3,4]]]
>>> a[-1]
[2, [3, 4]]
>>> a[-1][-1]
[3, 4]
>>> a[-1][-1][-1]
4

Let's say you had a different a.
a = [1, 1, 1, 1, 1, 1,[1, 1, 1, 1, 2,[1, 1, 1, 3,4]]] The code above will still give you the last element.

>>> a = [1, 1, 1, 1, 1, 1,[1, 1, 1, 1, 2,[1, 1, 1, 3,4]]]
>>> a[-1]
[1, 1, 1, 1, 2, [1, 1, 1, 3, 4]]
>>> a[-1][-1]
[1, 1, 1, 3, 4]
>>> a[-1][-1][-1]
4

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.