Jump to content

Assigning Values to an Array: Difference between revisions

Line 386:
 
To change existing item, (raise IndexError if the index does not exists):
<python>
array[index] = value
</python>
 
To append to the end of the array:
<python>
array.append(value)
</python>
 
It's also possible modify Python lists using "slices" which can replace, remove or insert elements into the array. For example:
 
<python>
mylist = [0,1,2,3]
mylist[1:3] = [1, 1.2, 1.3]
print mylist
## >>> [0, 1, 1.2, 1.3, 3]
## We've replaced 1 and 2 with 1, 1.2 and 1.3, effectively inserting 1.2 and 1.3 while removing the original third element (2)
</python>
 
Hint: slice notation should be read as: "from starting index '''up to''' (but '''not including''') ending index" -- a slice of [1:2] only references the single element sub-list containing the second item. To remember that they are zero based one might even read the slice more verbosely as: "from the n items past the beginning of the list, up to (but not including) ..."
 
It's even possible (though obscure) to use extended slices with a "stride" to replace every ''n''th element of a list using something like:
 
<python>
mylist = [0,1,2,3]
mylist[0:4:2] = ['x', 'y'] # can also be written as mylist[::2] in this case, to cover the whole list
print mylist
## >>> ['x', 1, 'y', 3]
</python>
 
Python lists also support ''.insert(),'' and ''.remove()'' methods, for cases where the slice syntax might be awkward, and a Python list can be treated like a stack by using the ''.pop()'' and ''.append()'' methods. Finally a whole list or other sequence can be appended to a list using the ''.extend()'' method.
 
<python>
mylist = [0,1]
mylist.extend([2,3])
print mylist
## >>> [0, 1, 2, 3]
## mylist.append([2,3]) would have appended one item to the list
## ... and that item would have been list containing two nested items
</python>
 
=={{header|Ruby}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.