Flipkart Interview Question | When to use list, set or dictionaries ?

Question

.

in progress 0
TheDataMonk 4 years 5 Answers 1058 views Grand Master 0

Answers ( 5 )

  1. list – if you require an ordered sequence of items.

    dict – if you require to relate values with keys

    set – if you require to keep unique unordered elements.

  2. Like all programming languages python also has some data structures. The in built data structures of python are – Lists,set,strings,tuples,dictionaries and frozen sets.

    In python we use Lists when we want to store certain strings or numbers or a combination of both together.
    Sets can be used to store only unique values and also it can be used to extract unique values from an already created list.
    Dictionaries can be used when we want to store data in a key value pair format.So that whenever we want a specific value we can directly access it using their respective keys.

  3. A list keeps order, dict and set don’t: when you care about order, therefore, you must use list (if your choice of containers is limited to these three, of course;-).

    dict associates with each key a value, while list and set just contain values: very different use cases, obviously.

    set requires items to be hashable, list doesn’t: if you have non-hashable items, therefore, you cannot use set and must instead use list.

    set forbids duplicates, list does not: also a crucial distinction. (A “multiset”, which maps duplicates into a different count for items present more than once, can be found in collections.Counter — you could build one as a dict, if for some weird reason you couldn’t import collections, or, in pre-2.7 Python as a collections.defaultdict(int), using the items as keys and the associated value as the count).

    Checking for membership of a value in a set (or dict, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list’s length in the average and worst cases. So, if you have hashable items, don’t care either way about order or duplicates, and want speedy membership checking, set is better than list.

  4. List when you have to maintain a collection of elements.
    Set when you have to keep only unique elements.
    Dictionary when you have to maintain a key-value pair.

  5. List : collection of items (same or different data type); ordered
    Set : Collection of unique items (duplicates are automatically removed)
    Dictionary : Key -Value pair , unordered , can be used when we want a value to be associated with one key
    { ‘a’ :’Delete’, ‘b’:’Update’}

Leave an answer

Browse
Browse