-1

I have a list of 21 lists of 10 elements each, I want to get a new list of 21 lists of the 3 elements first elements of the previous ones.

Like if I have [[1,2],[3,4]] and I wanted to get [1,3] (or [[1],[3]]).

I know how to get this by a loop, but I would like to use a more compact way.

In python we can use a[:3] for a simple list for example, but is there anyway to use something like a[:][:3] (like in MATLAB a(:,1:3)) to get inside the lists in the list?

AMC
  • 2,642
  • 7
  • 13
  • 35
arthll
  • 27
  • 1
  • 3

2 Answers2

0

Try:

# first 3 items of list in big list    
small_list = [l[:3] for l in big_list]

Code:

big_list = [[1,2,3,4,5,6,7,8,9,10],["a","b","c","d","e","f","g","h","i","j"],[10,20,30,40,50,60,70,80,90, 100]]

small_list = [l[:3] for l in big_list]

print (small_list)

Output:

[[1, 2, 3], ['a', 'b', 'c'], [10, 20, 30]]
Thaer A
  • 2,243
  • 1
  • 10
  • 14
0

It is not possible with native Python to acquire a range a elements for each sublist of a list. Apart from list comprehension, the closest you can do is to use map:

oldList = [[1,2,3,4,5,6,7,8,9,10],["a","b","c","d","e","f","g","h","i","j"],[10,20,30,40,50,60,70,80,90, 100]]
newList = list(map(lambda l: l[:3], oldList))

However, you can download and import the numpy library, which has a syntax that resembles the one that Matlab has:

import numpy as np

oldList = np.array([[1,2,3,4,5,6,7,8,9,10],["a","b","c","d","e","f","g","h","i","j"],[10,20,30,40,50,60,70,80,90, 100]])
newList = big_list[:,0:3]

print(newList)

This will return:

[['1' '2' '3']
 ['a' 'b' 'c']
 ['10' '20' '30']]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29