@@ -47,22 +47,51 @@ def __repr__(self):
4747 def __getitem__ (self , index ):
4848 """
4949 Indexing Support. Used to get a node at particular position
50+ >>> linked_list = LinkedList()
51+ >>> for i in range(0, 10):
52+ ... linked_list.insert_nth(i, i)
53+ >>> all(str(linked_list[i]) == str(i) for i in range(0, 10))
54+ True
55+ >>> linked_list[-10]
56+ Traceback (most recent call last):
57+ ...
58+ ValueError: list index out of range.
59+ >>> linked_list[len(linked_list)]
60+ Traceback (most recent call last):
61+ ...
62+ ValueError: list index out of range.
5063 """
51- if index < 0 :
52- raise ValueError ("Negative indexes are not yet supported " )
64+ if not 0 <= index < len ( self ) :
65+ raise ValueError ("list index out of range. " )
5366 for i , node in enumerate (self ):
5467 if i == index :
55- return node . data
68+ return node
5669
5770 # Used to change the data of a particular node
5871 def __setitem__ (self , index , data ):
72+ """
73+ >>> linked_list = LinkedList()
74+ >>> for i in range(0, 10):
75+ ... linked_list.insert_nth(i, i)
76+ >>> linked_list[0] = 666
77+ >>> linked_list[0]
78+ 666
79+ >>> linked_list[5] = -666
80+ >>> linked_list[5]
81+ -666
82+ >>> linked_list[-10] = 666
83+ Traceback (most recent call last):
84+ ...
85+ ValueError: list index out of range.
86+ >>> linked_list[len(linked_list)] = 666
87+ Traceback (most recent call last):
88+ ...
89+ ValueError: list index out of range.
90+ """
91+ if not 0 <= index < len (self ):
92+ raise ValueError ("list index out of range." )
5993 current = self .head
60- # If list is empty
61- if current is None :
62- raise IndexError ("The Linked List is empty" )
6394 for i in range (index ):
64- if current .next is None :
65- raise IndexError ("list index out of range" )
6695 current = current .next
6796 current .data = data
6897
@@ -163,8 +192,15 @@ def test_singly_linked_list() -> None:
163192 assert linked_list .delete_head () == 0
164193 assert linked_list .delete_nth (9 ) == 10
165194 assert linked_list .delete_tail () == 11
195+ assert len (linked_list ) == 9
166196 assert str (linked_list ) == "->" .join (str (i ) for i in range (1 , 10 ))
167197
198+ assert all (linked_list [i ] == i + 1 for i in range (0 , 9 )) is True
199+
200+ for i in range (0 , 9 ):
201+ linked_list [i ] = - i
202+ assert all (linked_list [i ] == - i for i in range (0 , 9 )) is True
203+
168204
169205def main ():
170206 from doctest import testmod
0 commit comments