Hello, I am confused when we have array in python why should we use set or lists they work almost similarly right? and array are bit faster that lists. I am using numpy arrays but a friend of mine uses sets and lists.
I am confused please explain what to use and when?

From my understanding:
Arrays are a thin wrapper on C style arrays. They can only contain objects of the same basic data-type, so they are more strongly typed - but they can only deal with numeric C-style data types. They are a lot more basic than lists or sets. Arrays are probably best used in situations where you know up front, how many items they will contain and that the array will not need to grow. But if you're going to be dealing with a dynamic set of data that could grow or shrink - you're probably better off using List or Set.

Sets can hold pretty much anything - as long as it is hashable. Objects in the set are sorted/ordered based on each objects hash values. Also, sets do not allow duplicates. And I'm not sure how set deals with hash collisions (where two different objects have the same hash-values). And because sets use hash-tables, lookups are pretty fast.
So if you are dealing with hashable types and you don't want duplicates (and you aren't worried about possible hash-collisions) - sets are the way to go.

Lists can hold pretty much anything and don't care about duplicates. Objects remain in the order in which they were added. If a list runs out of space and needs to reallocate - it will reallocate much more space than it needs. So lists can become quite large. But this does mean that they can be appended to efficiently, because reallocations will occur less often.

So to sum up:
Lists should be adequate for most uses - especially if it is possible that the data-set will grow to be large. Arrays are really only useful for numeric data. Sets can only be used with hashable types, with no duplication.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.