+ 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.
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]
+ 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 ^^
+ 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]
+ 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.
+ 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)
0
Hey Jerry Hobby,
Please visit this code:-)
This is my code: https://code.sololearn.com/c81FYo8eJ8u9/?ref=app
Hope this will help youđ
- 2
3245