miércoles, 13 de julio de 2022

List vs. tuple vs. set vs. dictionary in Python

 


MADHU SRAVANA VALLI

Python Collections are used to store data, for example, lists, dictionaries, sets, and tuples, all of which are built-in collections.

ListsTuplesSetsDictionaries
A list is a collection of ordered data.A tuple is an ordered collection of data.A set is an unordered collection.A dictionary is an unordered collection of data that stores data in key-value pairs.

Various ways to create a list

Various ways to create a tuple

How to create a set

How to create a dictionary

The fundamental distinction that Python makes on data is whether or not the value of an object changes. An object is mutable if the value can change; else, the object is immutable.

Lists are mutable.Tuples are immutable.Sets are mutable and have no duplicate elements.Dictionaries are mutable and keys do not allow duplicates.
Lists are declared with square braces.Tuples are enclosed within parenthesis.Sets are represented in curly brackets.Dictionaries are enclosed in curly brackets in the form of key-value pairs.

Python has a set of built-in methods that are used on these collections. They are:-

The append() method adds a single item at the end of the list without modifying the original list.An element cannot be added to the tuple as it is immutable.The set add() method adds a given element to a set.The update() method updates the dictionary with the specified key-value pairs
The pop() method removes the item at the given index from the list and returns it.Tuples are immutable.The pop() method removes a random item from the set.The pop() method removes the specified item from the dictionary.
The sort() method sorts the elements of a given list in a specific ascending or descending order.Though tuples are ordered, the elements cannot be sorted.Elements in the set cannot be sorted as they are unordered.sorted() method is used to sort the keys in the dictionary by default.
index() searches for a given element from the start of the list and returns the lowest index where the element appears.Searches the tuple for a specified value and returns the position of where it was found.The index of a particular element is not retrieved as they are unordered.The get() method returns the value of the item with the specified key.
The count() method returns the number of times the specified element appears in the list.The count() method returns the number of times a specified value occurs in a tuple.There are no count() methods in sets as they do not allow any duplicates.The count() method is not defined in the dictionary.
The reverse() method reverses the elements of the list.The reverse() method is not defined in tuples, as they are unchangeableThe sets are unordered, which refrains from applying the reverse() methodThe elements cannot be reversed, as the items in the dictionary are in the form of key-value pairs