Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through a list of lists in python?

Tags:

python

I have a list of lists like this.

documents = [['Human machine interface for lab abc computer applications','4'],
             ['A survey of user opinion of computer system response time','3'],
             ['The EPS user interface management system','2']]

Now i need to iterate through the above list and output a list of strings, as shown below (without the numbers in the original list)

documents = ['Human machine interface for lab abc computer applications',
             'A survey of user opinion of computer system response time',
             'The EPS user interface management system']
like image 392
ChamingaD Avatar asked Feb 05 '12 16:02

ChamingaD


People also ask

How do you iterate through a list without a loop in Python?

Looping without a for loopGet an iterator from the given iterable. Repeatedly get the next item from the iterator. Execute the body of the for loop if we successfully got the next item. Stop our loop if we got a StopIteration exception while getting the next item.


1 Answers

The simplest solution for doing exactly what you specified is:

documents = [sub_list[0] for sub_list in documents]

This is basically equivalent to the iterative version:

temp = []
for sub_list in documents:
    temp.append(sub_list[0])
documents = temp

This is however not really a general way of iterating through a multidimensional list with an arbitrary number of dimensions, since nested list comprehensions / nested for loops can get ugly; however you should be safe doing it for 2 or 3-d lists.

If you do decide to you need to flatten more than 3 dimensions, I'd recommend implementing a recursive traversal function which flattens all non-flat layers.

like image 118
machine yearning Avatar answered Sep 24 '22 22:09

machine yearning