1

I am getting some strange results with extracting sublist.

list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Switching the first and second index produces the same results.

list[:][1]
Out[8]: [4, 5, 6]

list[1][:]
Out[9]: [4, 5, 6]

and if I do this, it gives me an error

list[0:1][1]
Traceback (most recent call last):

  File "<ipython-input-10-93d72f916672>", line 1, in <module>
 list[0:1][1]

IndexError: list index out of range

Is this some known error with python 2.7?

Roy
  • 53
  • 5
  • 2
    A slice is not inclusive of the last number, e.g. `[1, 2, 3][0:1] == [1]` therefore `[1, 2, 3][0:1][1]` will always create an `IndexError` (indexes start at `0`). In your example `lst[0:1] == [[1,2,3]]`, i.e. a list with only `1` item that is a list. Not sure why you are using slices for indexing `[:]` is expensive and unnecessary. Note: don't call your variable `list` it hides python's builtin type. – AChampion Sep 07 '17 at 18:57
  • 1
    Its not [1,2,3] its [[1,2,3]], both are very different! See my answer for more details – Rathan Naik Sep 07 '17 at 19:07
  • @RathanNaik I see now, thanks! Is there anyway to slice a column of list? For example, to get a list of the first element of sublists, [1,4,7]? – Roy Sep 07 '17 at 19:53
  • 1
    Yes there are many ways to do that here is my way, **list = [ i[0] for i in list ]** – Rathan Naik Sep 07 '17 at 19:56
  • Let me know if it helps – Rathan Naik Sep 07 '17 at 19:57
  • @RathanNaik Yes, it does the work, thanks – Roy Sep 07 '17 at 20:05
  • @Roy You are welcome. – Rathan Naik Sep 07 '17 at 20:06

2 Answers2

2

When you slice a list say 0:5, list will get sliced excluding list[5]

Ex : l = [0,1,2,3,4,5]
l = l[0:5]
now l is [0,1,2,3,4]

Its same situation here, so its only 0th element present in list that is your list after slice is [[1,2,3]], which means 0th element is [1,2,3] and 1st element is out of range.!

Rathan Naik
  • 993
  • 12
  • 25
1

If you observe the Slice list[0:1], It creates a list of size one, Also in Python indexing starts from 0 therefore, accessing index 1 of list with size one will raise an Error list index out of range

list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  //Original List

list[0:1] // [[1,2,3]]   A list of size 1

list[0:1][1] // This will return list index out of range

list[0:1][0]  // [1,2,3]
Ishpreet
  • 5,230
  • 2
  • 19
  • 35