Home > database >  Slicing 2D Python List
Slicing 2D Python List

Time:04-05

Let's say I have a list:

list = [[1, 2, 3, 4],
        ['a', 'b', 'c', 'd'], 
        [9, 8, 7, 6]]

and I would like to get something like:

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

hence I tried going with this solution

print(list[0:][1:])

But I get this output

[['a', 'b', 'c', 'd'],
 [9, 8, 7, 6]]

Therefore I tried

print(list[1:][0:])

but I get precisely the same result.

I tried to make some research and experiments about this specific subject but without any result.

CodePudding user response:

You want the 1 to end element of every row in your matrix.

mylist = [[1, 2, 3, 4],
        ['a', 'b', 'c', 'd'], 
        [9, 8, 7, 6]]

new_list = [row[1:] for row in mylist]

CodePudding user response:

First - don't name your list "list"!

a = [[1, 2, 3, 4],
    ['a', 'b', 'c', 'd'],
    [9, 8, 7, 6]]
b = [x[1:] for x in a]
print(b)

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

CodePudding user response:

I want explain, what have you done by this

print(list[0:][1:])
print(list[1:][0:])

Firstly note that python use indices starting at 0, i.e. for [1,2,3] there is 0th element, 1th element and 2nd element.

[0:] means get list elements starting at 0th element, this will give you copy of list, [1:] means get list elements starting at 1th element, which will give you list with all but 0th element. Therefore both lines are equivalent to each others and to

print(list[1:])

You might desired output using comprehension or map as follows

list1 = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [9, 8, 7, 6]]
list2 = list(map(lambda x:x[1:],list1))
print(list2)

output

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

lambda here is nameless function, note that comprehension here is more readable, but might be easier to digest if you earlier worked with language which have similar feature, e.g. JavaScript's map

  • Related