Lists, Tuples, and Sets—When to Use Which?

Categories: Tech | Pubby Cash Received:  0 | Click to Award

A data structure that stores an ordered collection of items in Python is called a list. In other words, a list holds a sequence of items. A list can have any number of elements and different data types. Moreover, a list can have another list as an element. Such a list is known as a nested list. Use lists whenever there is data that will change. Since lists are mutable, it is easy to replace an existing value or insert a new value into a list. Tuples, on the other hand, are the same as lists with the only difference being their inability to be modified. A tuple is stored exactly as it is. If you want to change a value in a tuple, you would have to create a new one. Tuples are used in scenarios where it is certain that the set of values belonging to some statement or a user-defined function will not change. Finally, a set is an unordered collection of simple objects in Python. In addition to being iterable and mutable, a set has no duplicate elements. Any set defined in Python is an instance of the set class. Compared to a list, a set is advantageous by having a highly optimized method for checking whether some element is contained in the set or not. Want more practice but don't know where to go? Amazon has this great book that allows you to problem solve with algorithms and data structures using Python. You should check it out!


Published from: Pennsylvania US
Liked by: H2O 

Daily Deals


MECHANICSBURG WEATHER