In: Computer Science
Difference between array and list? Explain in your own words.
Arrays and Lists are both data strutures used for storing data.
The difference between an array and a list are as follows:
1)An array is used to store homogeneous data values(i.e of the same data type) while a list can be used to store heterogeneous data values(i.e of different data types). Eg: A=[1,2,3,4] is an array which consists of integer data type
L=[1.2.1,'a'] is a list which contains integer,floating point and character data type (Heterogeneous).
2)If you want to perform arithmetic on the elements present we use an Array but arithmetic operations on all the list elements is not possible.Eg: A=[2,4,6,8] is an array which consists of integer data type if I perform the operation A/2 then my new array would look like A=[1,2,3,4],while on the other hand considering a list with the same elements as the array example L=[2,4,6,8] if i perform the operation L/2 i would get an error message.
3)Coming to the memory aspect an Array is essentially a static data type which means that once you intialize the size of the array you cannot change or modify it during execution based on user's input.This creates a problem as if you initialize a very large size while the user enters few values a lot of memory is simply wasted or on the flip side if you initialize an array with a small data size then the user may not be able to enter his entire input which creates a faulty program.
Hmm so in no way you would be able to read the mind of an anonymus user and create a perfect array pertaining to that size.But what if you could allocate memory at the exact same time when the user enters his input based on the size he enters.
This is where dynamic allocation comes into the picture and Lists are dynamic data types so you wouldnt have to worry about wastage of memory or a faulty program.
The list memory is allocated during execution when the user enters the size.