Difference between list, tuples and sets in python

Generally, lists, tuples, and sets are collections of items that are separated by commas. Let's take a look at each of them individually before focusing on their differences.

List:

The Python list is a general data structure widely used in Python programs. They are used in other languages like Java and C# and are often referred to as dynamic arrays. Lists are mutable and orderly data types that allow them to be indexed and sliced. A list can contain different types of objects, including other list objects. 

In simpler terms, lists are heterogeneous containers for storing items.

Major characteristics of a list

  • List are mutable. This simply means one can modify, replace and even change the order of the items after creation.
  • List can store any type of element, whether booleans, strings, or integers. 
  • List is a datatype in Python containing collections of items separated by commas and housed by a square bracket.
#create a list
list1 = [1, 2, "John", "brain", True]
print(list1)

#Replace or change items in a list
list2 = ['South Africa', 'Nigeria', 'Drake', 'Daniel']
list2[0] = "Japan"
print(list2)



Tuple:

A tuple is an immutable list of values. Tuples are one of python's simplest and most common collection types and can be created with the comma operator(value = 1, 2, 3).

Syntactically, a tuple is a comma-separated list of values.

tuples = "broom", "bell", "jug"

Although not necessary, it is conventional to enclose tuples in parenthesis.

tuples = ("broom", 1, "jug")

To create a single tuple, it is necessary to attach a trailing comma.

tuples = ("jug",)
tuples = "jug",

Major characteristics of a tuples

  • A tuple is immutable that is one cannot add or modify items once the tuple is initialized.
  • A tuple is conventionally defined under parenthesis
  • Tuples can store any type of element.

Sets:

Sets are unordered collections of unique objects. Sets are mutable and new elements can be added once sets are defined. Sets have no duplicate. Sets can be used to keep track of the element multiplicity.

fruits = {"pineapple", "mango", "orange", "grape", "banana", "strawberry", "mango"}
print(fruits) #duplicate will be removed

Major characteristics of a set

  • Sets are unordered collections of items.
  • It is defined under a curly bracket {}.
  • Sets are mutable 

Differences between list, tuple, and set.

List Tuple Set
List are ordered collection of items Tuple are ordered collection of items Sets are unordered collections of items
They are mutable They are immutable  They are mutable 
They are defined by a square bracket [ ]  They are defined by parenthesis ()  They are defined by curly bracket {}