Reputation: 2238
I created a list in Python as follows
gona = [[1,5,6],[3,7,10]]
This is a list of lists. What I want to do is get second entry in both inner lists. I tried to following.
gona[:][1]
but this gives me the second list.
[3,7,10]
When I changed the order as follows,
gona[1][:]
it gives the same result. What is the reason for this? How can do what I have stated above? I'm using Python 2.7.3 in Windows 7. I have tried this with Python 2.7.5 in Ubuntu 13.10 as well.
Upvotes: 0
Views: 62
Reputation: 5048
if you want to get an element in the inner lists or a default value in the case that element does not exists you may use this:
index = 1
[row[index] if len(row) > index else None for row in gona] # None is the default value here
Upvotes: 2
Reputation: 1124738
Use a list comprehension:
[g[1] for g in gona]
list[:]
creates a full slice copy of the original list, it does not mean 'loop through this list for the next operation'.
Python list objects can hold any type of object, there is no slicing syntax that lets you select from contained list objects apart from a list comprehension, because Python cannot know up front that you only have indexable objects contained.
Perhaps you got confused with numpy.array
objects, which can make such assumptions and implement a richer slicing syntax.
Upvotes: 2
Reputation: 251578
As you said, it is a list of lists. There is no simple indexing way to get the second entry in both inner lists, because the lists aren't oriented that way (i.e., columnwise). That is, the outer list does not "know" that its contents are other lists whose elements you want to get. All you can get from the outer list is one of the inner lists. (Nothing even guarantees that every inner list has a second element. You could have done gona = [[1], [], [1, 2, 3, 4, 5]]
.)
You can do [row[1] for row in gona]
.
Upvotes: 2