Difference between Set and List in Python
In this article, we will discuss the difference between Set and list in Python. Set and list are the Data Structures in Python, which are used for storing and organizing the data in an effective manner.
List
The list in Python is like an array of dynamic size, which can be declared in different languages such as vector in C++ language and ArrayList in Java language. It is not compulsory for a list in Python to be homogenous, and this characteristic of the list makes it one of the powerful tools of Python.
The following are the important characteristics of list:
- It is the datatype offered by Python. The users can write it as the list whose values can be separated by a comma and are written between the square brackets.
- It can be converted into different data types, and the users can store any element of data in it. Therefore, the List is mutable.
- It is ordered.
Example:
Output:
tutoraspire data List: [] The tutoraspire List of numbers: [12, 24, 64, 18, 3, 201, 65, 35, 27, 29, 58, 42, 87, 30, 28, 79, 4, 90] List Items: let's Python learn tutoraspire from List1 = [9, 3, 6, 19, 67, 'Hey', 'tutoraspire', 78, 2, 1] List2 = [9, 3, 6, 19, 67, 78, 'Hey', 'tutoraspire', 2, 1] False
Set
Sets are the unordered collection of data types in Python, which are mutable and iterable. Sets do not have any repetition of identical elements. One of the major advantages of using sets data storing tool in Python over List is that it offers highly optimized methods for checking the presence of specific items present in the set.
The following are the important characteristics of set:
- It is the unordered collection of items or data types in Python.
- The order of elements stored in it is not fixed. The order of set elements can be changed.
- A set of elements is defined between curly brackets { }.
- Although only immutable elements are stored in sets, it is mutable.
Example:
Output:
Intial tutoraspire Set: set() Storing the set by using the Object: {'t', 'v', 'a', 'r', 'T', 'l', 'n', 'y', 'e', ' ', 'h', 'P', 'p', 'f', 'o', 's', 'i', 'J', 'm'} Storing the set by using the List: {'tutoraspire', "let's", 'learn', 'from', 'Python'}
Lists vs. Sets
Lists | Sets |
---|---|
Lists are Ordered. | Sets are Unordered. |
Lists are Mutable. | Sets are mutable but only stored immutable elements. |
Elements can be changed or replaced in Lists. | Elements cannot be changed or replaced. |