In: Computer Science
Using the Python Program. Can an array hold a mixture of types i.e. int, float, string, array within the same array?
Show a code segment to remove the last element from a 15 element array named myStuff[]. Please explain the code.
By arrays, I’m assuming you meant Python lists since there are no built in arrays in Python. And YES, the python lists supports all kind of objects to be added to an array. For example, consider the below code.
arr=[1,2,3,'Food',5.5,True]
The arr array/list has 6 elements of type integers, string, float and boolean. There is absolutely no problem with the above code.
Show a code segment to remove the last element from a 15 element array named myStuff[].
This can be done in many ways. Some of them are listed below.
a) myStuff.pop(14)
This statement will remove element at index 14 (15th element) from myStuff, if you are sure that the array has 15 elements.
b) myStuff.pop(len(myStuff)-1)
len() returns the size of an array, subtracting one will get you the index of last element in the array, so the pop method removes the element at that index.
c) myStuff.pop(-1)
This is one of the best things that I like about python. It allows negative indicing. If you pass a negative value n as the index to pop method, it will remove n th element from rear. So in this case, this will remove 1st element from back, or in other words, the last element from front.
Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks