-3

So, for example, with the list below. How can I extract and print just the number 408?

 a = [[366, 408, 'Help'], [143, 99, 'Me'], [695, 140, 'Please']] 
 print a[0]
1
  • The same way you extracted the first list? What have you tried for this specific problem? Commented Feb 10, 2017 at 8:55

1 Answer 1

0

The short answer is to index the first sublist and then index the element of that sublist that you want to see.

In the first case below, we simply print the sublist by indexing a[0]. In the second case, we print the second element of the first sublist by indexing a[0][1] (NOTE: Python indexes start at 0)

>>> a = [[366, 408, 'Help'], [143, 99, 'Me'], [695, 140, 'Please']] 
>>> print a[0]     
[366, 408, 'Help']

>>> print a[0][1]
408

If per chance, you want to extract all of the second items from each of the sublists, you can use a Python for loop:

>>> for sublist in a:
        print sublist[1]
408
99
140

To address the comment asking about how to extract the first and second items:

>>> temp = []
>>> for sublist in a:
        temp.extend(sublist[0:2])
        if len(temp) == 4:       # print temp if it contains 4 elements
            print(temp)
            temp = temp[2:]      # remove the first two elements
Sign up to request clarification or add additional context in comments.

2 Comments

A loop is exactly what I need. I need all of the first and second items from each sublist. Thanks!
Do you know how to extract the first and second items from each sublist AND the first and second items from the next sublist? So like, (366, 408, 143, 99) then (143,99,695,140).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.