Qubix
Qubix

Reputation: 4353

slice a list up to a given element

If you have a list my_list = ['a', 'd', 'e', 'c', 'b', 'f'] and you want to construct a sublist, containing all elements up to a given one, for example my_list_up_to_c = ['a', 'd', 'e'], how can this be done in a way that scales easily? Also can this be made faster by using numpy arrays?

Upvotes: 1

Views: 402

Answers (4)

Qiang Xu
Qiang Xu

Reputation: 4803

This might have better performance for big lists, coz it only needs one pass:

sub_list = []
for elem in my_list:
    sub_list.append(elem)
    if elem == target_elem:
        break

Upvotes: 1

Elmex80s
Elmex80s

Reputation: 3504

The itertools solution

In[9]: from itertools import takewhile
In[10]: my_list = ['a', 'd', 'e', 'c', 'b', 'f'] 
In[11]: list(takewhile(lambda x: x != 'c', my_list))
Out[11]: ['a', 'd', 'e']

In Haskell it would be

takeWhile ((/=) 'c') "adecbf"

Upvotes: 2

Ralf
Ralf

Reputation: 16505

The least amount of code would probably be using .index() (note that this searches till the first occurence of the element in said list):

>>> my_list = ['a', 'd', 'e', 'c', 'b', 'f']
>>> my_list
['a', 'd', 'e', 'c', 'b', 'f']
>>> my_list[:my_list.index('c')]          # excluding the specified element
['a', 'd', 'e']
>>> my_list[:my_list.index('c')+1]        # including the specified element
['a', 'd', 'e', 'c']

The time complexity of the call to .index() is O(n), meaning it will at most iterate once over the list. The list slicing has complexity O(k) (according to this source), meaning it depends on the size of the slice.

So in the worst case the element you look for is at the end of the list, so your search will run till the end of the list (O(n)) and the slice will copy the whole list as well (also O(n)), resulting in a worst case of O(2n) which is still linear complexity.

Upvotes: 4

Alexander Rossmanith
Alexander Rossmanith

Reputation: 334

Use index() to get the first occurrence of a list item. Then use the slice notation to get the desired part of the list.

>>> my_list = ['a', 'd', 'e', 'c', 'b', 'f']
>>> my_list[:my_list.index('c')]
['a', 'd', 'e']

Upvotes: 2

Related Questions