Python @ DjangoSpin

Python: When to use which data structure

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

When to use which data structure in Python

When to use which data structure in Python

Each data structure has an array of associated methods and attributes, and each one of them can do different things. Here are a few tips on how to choose the right one to suit your needs:

  • Use a list if you have a mixed collection of data, capable of being modified and added to, that you want to be able to refer to using indexes.
  • Use a set if you want a collection of unique yet mutable elements, and you require to perform mathematical operations like union, intersection etc. on the elements. Also, keep in mind, that sets cannot hold mutable types such as dictionaries, sets or lists. Frozen sets work, though.
  • Use a tuple if you know that your data is not going to undergo any changes, especially if you are focusing on the performance of your programs. Owing to their immutability, python knows just how much memory to allocate for the data, and hence are great for performance.
  • Use a dictionary if you want to store key-value pairs, which not only implement logical associations, but also are mutable and offer a fast lookup i.e. fast retrieval of values because of custom keys. Keep in mind that sets, lists and dictionaries(all mutable types) cannot assume the roles of a dictionary key. Frozen sets can work as a dicitonary key.
  • Use a frozen set if want a collection of unique elements in an immutable way.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply