+ 7

I’m exploring Python list slicing and found an odd behavior. Can you tell me why I get this result and how do I do it right?

mylist = [[1,2,3],[4,5,6],[7,8,9]] # outputs 5, as expected print(mylist[1][1]) # outputs [7,8,9] as expected print(mylist[2]) # I want to output just col 1 only. [1,4,7] # I know I can use a for loop or numpy for this. But # can I do this using slice syntax? I've tried these, # but ALL of these print the same [1,2,3]. Odd. print(mylist[0:2][0]) print(mylist[0:-1][0]) print(mylist[0:][0]) ### NOTE: I know I can accomplish this with a for loop or with numpy. I’m trying to check if it can be done with list slice syntax.

22nd Mar 2021, 11:17 PM
Jerry Hobby
Jerry Hobby - avatar
8 Answers
+ 9
with only slicing you cannot... however, there is a way between slicing and for loop... list comprehension: col0 = [v[0] for v in mylist]
22nd Mar 2021, 11:20 PM
visph
visph - avatar
+ 8
you may have high probabilies to get quick answer with a well formed question: accurate title, useful tags, and good description ;) if only all (or at least most of) sololearners could post such good redacted question ^^
22nd Mar 2021, 11:31 PM
visph
visph - avatar
+ 6
Jerry Hobby , this is also working: print([i[0] for i in mylist]) # output is [1,4,7] by changing the value in [0] to 1, output is [2,5,8], changing it to 2, result is [3,6,9]
23rd Mar 2021, 9:55 AM
Lothar
Lothar - avatar
+ 5
visph That’s precisely what I was looking for. I thought I ran across a way sometime in the past. This was the method I was “trying” to remember. I appreciate your quick answer.
22nd Mar 2021, 11:27 PM
Jerry Hobby
Jerry Hobby - avatar
+ 1
# Pythonic slicing without for loop and the output is a list in 1 line! Feel The Power of PYTHON đŸ’Ș🙏 l = [[1,2,3],[4,5,6],[6,7,8]] elems = [l[0][0],l[1][0],l[2][0]] print(elems)
24th Mar 2021, 1:11 PM
iTech
iTech - avatar
0
Hey Jerry Hobby, Please visit this code:-) This is my code: https://code.sololearn.com/c81FYo8eJ8u9/?ref=app Hope this will help you🙂
24th Mar 2021, 12:36 PM
Adarsh Addee
Adarsh Addee - avatar
- 2
3245
25th Mar 2021, 6:00 AM
Md Aziz
Md Aziz - avatar