5

I have a nested list as shown below:

A = [('a', 'b', 'c'),
     ('d', 'e', 'f'),
     ('g', 'h', 'i')]

and I am trying to print the first element of each list using the code:

A = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
print A[:][0]

But I get the following output:

('a', 'b', 'c')

Required output:

('a', 'd', 'g')

How to get this output in Python?

5 Answers 5

6

A[:] just creates a copy of the whole list, after which you get element 0 of that copy.

You need to use a list comprehension here:

[tup[0] for tup in A]

to get a list, or use tuple() with a generator expression to get a tuple:

tuple(tup[0] for tup in A)

Demo:

>>> A = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
>>> [tup[0] for tup in A]
['a', 'd', 'g']
>>> tuple(tup[0] for tup in A)
('a', 'd', 'g')
Sign up to request clarification or add additional context in comments.

Comments

2

You can transpose a list of lists/tuples with zip(*list_of_lists) then select the items you want.

>>> a
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
>>> b = zip(*a)
>>> b
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
>>> b[0]
('a', 'd', 'g')
>>> 
>>> c = zip(*a)[0]
>>> c
('a', 'd', 'g')
>>>

Comments

1

You can also do it this way:

>>> A = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
>>> map(lambda t:t[0], A)
['a', 'd', 'g']
>>> tuple(map(lambda t:t[0],A))
('a', 'd', 'g')

Comments

1

Python lists don't work very well as multi-dimensional arrays. If you're willing to add an extra dependency(e.g. if you're going to do a lot of array manipulation), numpy allows you to use the almost the exact syntax you're looking for

import numpy as np
A = np.array([('a', 'b', 'c'),
              ('d', 'e', 'f'),
              ('g', 'h', 'i')])

This outputs the row as an np.array(which can be accessed like a list):

>>> A[:,0]
array(['a', 'd', 'g'])

To get the first row as a tuple:

>>> tuple(A[:,0])
('a', 'd', 'g')

Comments

1

You can also get the behavior you want using pandas as follows:

In [1]: import pandas as pd

In [2]: A = [('a', 'b', 'c'),
     ('d', 'e', 'f'),
     ('g', 'h', 'i')]

In [3]: df = pd.DataFrame(A)

In [4]: df[:][0]
Out[4]:
0    a
1    d
2    g
Name: 0, dtype: object

In [5]: df[:][0].values
Out[5]: array(['a', 'd', 'g'], dtype=object)

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.