Posts

Showing posts with the label Python(List Comprehension)

How to find the index or indexes of an item in a list in Python

Image
  A simple answer to this is using string function index() , >>> l = ['a','b','c'] >>> l.index('b') 1 The offical document states: list . index ( x [, start [, end ]]) Return zero-based index in the list of the first item whose value is equal to  x . Raises a  ValueError  if there is no such item. The optional arguments  start  and  end  are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument. The caveat follows The index() method of the list object is so inefficient when your list becomes way to big. It checks every element from the start until it finds the element or to the end. When you don't know roughly the place of your searching element in such a large list, you should consider another data structure to avoid this overhead.   If you do know the rough place w

How can we make a flat list out of a list of lists? (Python List Comprehension)

Image
How can we make a flat list out of a list of lists? l = [[1,2,3],[3,4,5],[6,7,8]] In order to achive this end, we can use for loops: Method 1 flat_list = [] for  sub_list in l:      for item in sub_list:          flat_list.append(item) And also we can use list comprehension, which is more efficient: Method 2 flat_list = [item for sub_list in l for item in sub_list] We can also use the itertools library: Method3 import itertools flat_list = list(itertools.chain(*l))