Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a new list with subset of list using index in python

A list:

a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8] 

I want a list using a subset of a using a[0:2],a[4], a[6:],

that is I want a list ['a', 'b', 4, 6, 7, 8]

like image 450
user2783615 Avatar asked Oct 08 '13 15:10

user2783615


People also ask

How do I add a list to a specific index?

Inserting an element in list at specific index using list. insert() In python list provides a member function insert() i.e. It accepts a position and an element and inserts the element at given position in the list.


2 Answers

Suppose

a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8] 

and the list of indexes is stored in

b= [0, 1, 2, 4, 6, 7, 8] 

then a simple one-line solution will be

c = [a[i] for i in b] 
like image 177
G. Cohen Avatar answered Oct 05 '22 22:10

G. Cohen


Try new_list = a[0:2] + [a[4]] + a[6:].

Or more generally, something like this:

from itertools import chain new_list = list(chain(a[0:2], [a[4]], a[6:])) 

This works with other sequences as well, and is likely to be faster.

Or you could do this:

def chain_elements_or_slices(*elements_or_slices):     new_list = []     for i in elements_or_slices:         if isinstance(i, list):             new_list.extend(i)         else:             new_list.append(i)     return new_list  new_list = chain_elements_or_slices(a[0:2], a[4], a[6:]) 

But beware, this would lead to problems if some of the elements in your list were themselves lists. To solve this, either use one of the previous solutions, or replace a[4] with a[4:5] (or more generally a[n] with a[n:n+1]).

like image 42
rlms Avatar answered Oct 05 '22 22:10

rlms