Posts

Showing posts with the label Python

Removing an Element from a Set - remove() v/s discard() - Python

Removing an element from a Set In any data structure or data set, adding or removing the data is essential. Set is one of the most important data structures in Python. Set is an unordered collection of data and does not hold duplicate data, this makes it different from the other data structures like List and Tuple. In this post, Let's take a look at couple of different ways of removing an element from a Set.  Using 'remove()' method Using 'discard()' method The purpose of both these methods is to remove an element (passed) from a set. So, What makes these methods different from each other? Read on to find out.  remove() Syntax set.remove(<element_to_be_removed>) remove() method accepts an element to be removed as an argument and removes the corresponding element from the set.  One thing to note here is that the element passed as an argument to remove method must present in the set . If the element is not found in the set, this method returns KeyError.  1 2 3 n...

Different Ways of Sorting Data in a List - Python

Image
Sorting Data in a List List is a collection of data (of different data types), much like an array. Like any data structure or data set, data in the list doesn't necessarily be in any specific order.  At times, depending on the use case we get to order the data in a specific sequence (Ascending, Descending or Reverse). There are couple of methods and functions for sorting the data in a list, which can be used depending on the use case.  sort() method  sorted() function reverse() method reversed() function  Let's have a look at each of these in detail.  sort() method Sort() method by default sorts the data in an ascending order. One important thing to remember about sort() method is that, it sorts the list in-place, meaning the list on which method is called would be sorted and the method would return None (no sorted list would be returned).  Syntax           list.sort(<key=None>, <reverse=False>) The two parameters ...