Set Vs List Python
Set in Python:
In Python set is a grouping of unsorted items. The set's elements must all be distinct and unchangeable, and the sets must eliminate duplicates. Sets can be changed after they are created because they are mutable.
In contrast to other Python collections, the set's elements do not have any associated indexes, making it impossible to access any set element directly using its index. However, we have two options: print them all at once, or loop through the set to obtain the list of elements.
Creating a Set in Python:
The curly braces can be used to enclose the immutable items, which are separated by commas, to create the set. Python also offers the set() method, which can be used to build a set using a sequence that has been passed.
CODE:
Planets = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"}
print(Days)
print("\r")
print(type(Planets))
print("\r")
print("repeating the set of elements ... ")
print("\r")
for i in Planets:
print(i)
print("\r")
print(len(Planets))
OUTPUT:
{'Mercury', 'Saturn', 'Neptune', 'Earth', 'Venus', 'Jupiter', 'Uranus', 'Mars'}
<class 'set'>
Repeating the set of elements ...
Mercury
Saturn
Neptune
Earth
Venus
Jupiter
Uranus
Mars
8
CODE EXPLANATION:
This code creates a set called "Planets" and assigns the values "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", and "Neptune" to it. The code then attempts to print the set "Days" to the console, but there is a typo in the code, and it should be "Planets". The code then uses the type() function to print the type of the "Planets" set, which is "set". Next, a for loop is used to iterate over the elements in the set "Planets" and print each planet one.
Creating a set using set() method:
CODE:
Planets = set(["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"])
print(Planets)
print(type(Planets))
for i in Days:
print(i)
OUTPUT:
{'Mercury', 'Saturn', 'Neptune', 'Earth', 'Venus', 'Jupiter', 'Uranus', 'Mars'}
<class 'set'>
Sunday
Tuesday
Saturday
Monday
Friday
Wednesday
Thursday
CODE EXPLANATION:
This code creates a set called "Planets" and assigns the values "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", and "Neptune" to it. The code then attempts to print the set "Days" to the console, but there is a typo in the code, and it should be "Planets". This code creates a set called "Planets" using the set() constructor and assigns the values "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", and "Neptune" to it. The code then prints the "Planets" set to the console. The type() function is used to print the type of the "Planets" set, which is "set". Next, a for loop is used to iterate over the elements in the set "Days". However, the code has a typo and should be "Planets". This code demonstrates how to create a set using the set() constructor and how to get the type of an object using the type() function. The code then uses the type() function to print the type of the "Planets" set, which is "set". Next, a for loop is used to iterate over the elements in the set "Planets" and print each planet one. Any element type may be present, including float, tuple, and integer. However, the set cannot contain mutable components (list, dictionary, or set). Consider the example below.
CODE:
# constructing a set with unchangeable elements
set1 = {1,2,3, "TutorialAndExample", 20.5, 14}
print(type(set1))
# making a set with mutable components
set2 = {1,2,3,["TutorialAndExample",4]}
print(type(set2))
OUTPUT:
<class 'set'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [21], in <cell line: 5>()
3 print(type(set1))
4 # making a set with mutable components
----> 5 set2 = {1,2,3,["TutorialAndExample",4]}
6 print(type(set2))
TypeError: unhashable type: 'list.'
CODE EXPLANATION:
In the code above, we also created sets, set1 and set2, each with one mutable element as a list. The set can only contain immutable elements because an error was raised when the type of set2 was checked.
Because curly braces are also employed to create a dictionary, creating a vacant set is slightly different. Python thus offers the set() method, which can be used to start creating an empty set without an argument.
# Curly braces left empty will produce a dictionary.
set1 = {}
print(type(set1))
# using the set() function, an empty set
set2 = set()
print(type(set2))
OUTPUT:
<class 'dict'>
<class 'set'>
CODE EXPLANATION:
This code demonstrates the difference between creating an empty dictionary and an empty set in Python.
The first line creates an empty dictionary using the curly braces {}. The object type is then printed using the type() function and returns "dict".
The second line creates an empty set using the set() function. The object type is then printed using the type() function and returns "set".
This code shows that an empty dictionary and an empty set are created differently in Python, and it is important to understand the difference between them.Duplicates are eliminated if we give the set the duplicate element.
set = {1,2,4,4,5,8,9,9,10}
print("Return set with special components:",set)
OUTPUT:
Return set with special components: {1, 2, 4, 5, 8, 9, 10}
CODE EXPLANATION:
This code creates a set called "set" and assigns the values 1, 2, 4, 5, 8, 9, and 10.
This code demonstrates how to create a Python set and display its contents using the print() function. Note that duplicates are automatically removed from a set, so even though the numbers 4 and 9 are repeated in the input, they only appear once in the set. The code then uses the print() function to display the message "Return set with special components:" followed by the set "set". When we printed the duplicate elements from the set in the code above, we could see several of them.
Adding Elements to the Set:
The add() and update() methods in Python can include a specific item in the set. The update() technique is applied to add multiple elements to a set, whereas the add() method only adds a single element. Consider the example below.
CODE:
Planets = {"Mercury", "Venus", "Mars", "Saturn", "Uranus", "Neptune"}
print("\r")
print("printing the original set:")
print(Planets)
print("\r")
print("Adding other Planets to the set:")
Planets.add("Earth")
Planets. add ("Jupiter")
print("Earth and Jupiter")
print("\r")
print("The modified set printed:")
print(Planets)
print("\r")
print("looping through the set elements:")
for i in Planets:
print(i)
OUTPUT:
printing the original set:
{'Saturn', 'Neptune', 'Uranus', 'Mercury', 'Venus', 'Mars'}
Adding other Planets to the set:
Earth and Jupiter
The modified set printed:
{'Earth', 'Saturn', 'Neptune', 'Uranus', 'Mercury', 'Venus', 'Jupiter', 'Mars'}
looping through the set elements:
Earth
Saturn
Neptune
Uranus
Mercury
Venus
Jupiter
Mars
CODE EXPLANATION:
This code creates a set called "Planets" and assigns the values "Mercury", "Venus", "Mars", "Saturn", "Uranus", and "Neptune" to it. The original set is printed on the console. Then two new values, "Earth" and "Jupiter", are added to the set using the .add() method. A message indicating the addition of these two planets is printed.
This adds how to create a Python set, add elements, and iterate over its elements. After adding these two planets, the modified set is printed again on the console. Finally, the code uses a for loop to iterate over the elements in the set and prints each planet in the set one by one. Python offers the update() method to add multiple items to a set. It accepts the argument of iterable.
CODE:
days = {"Monday", "Friday", "Saturday", "Sunday"}
print("printing the original set ... ")
print(days)
print("\r")
print("updating the original set by adding:")
print("Tuesday, Wednesday, Thursday")
days.update(["Tuesday", "Wednesday", "Thursday"])
print("\nprinting the modified set ... ")
print(days)
OUTPUT:
printing the original set ...
{'Friday', 'Saturday', 'Monday', 'Sunday'}
updating the original set by adding:
Tuesday, Wednesday, and Thursday
printing the modified set ...
{'Tuesday', 'Sunday', 'Saturday', 'Monday', 'Wednesday', 'Friday', 'Thursday'}
CODE EXPLANATION:
This code demonstrates how to create a set in Python, add elements to it using the .update() method, and print the updated set. This code creates a set called "days" and assigns the values "Monday", "Friday", "Saturday", and "Sunday" to it. The original set is then printed to the console. The code then uses the .update() method to add the values "Tuesday", "Wednesday", and "Thursday" to the set "days". Finally, the modified set is printed on the console.
List in Python:
The order of different data types is stored in a list in Python. A list is a grouping of values or things of various kinds. Because Python lists are mutable, we can change an element's state after it has been created. A comma (,) is used to separate the list's items, and square brackets ()enclose them.
A list, a sequence type, is used to store data collection. The list is the most widely used and reliable form, even though Python has six data types that can hold sequences. Tuples and String are similar sequence data formats.
Python lists are the same as dynamically scaled arrays defined in other languages, like Java's Array List and C++'s vector. Using symbols [] and commas to separate each item, a list is a collection of items.
CODE:
# a simple list
list1 = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
list2 = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
# printing the list
print(list1)
print(list2)
# printing the type of list
print(type(list1))
print(type(list2))
OUTPUT:
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
<class 'list'>
<class 'list'>
CODE EXPLANATION:
This code creates two lists, list1 and list2. List 1 contains the names of eight planets, while list 2 contains the names of seven days of the week. The code then uses the print() function to display the contents of both lists. The contents of the list1 are displayed first, followed by list 2. Finally, the code uses the print() function to display the data type of both lists. In this case, both lists are of type list, a built-in data type in Python for storing ordered collections of items. This code demonstrates how to create Python lists and display their contents and data type.
Characteristics of List:
- Lists are organised.
- The list's element can be accessed by index.
- The mutable type includes lists.
- The list types are mutable.
- The number of different elements can be stored in a list.
Checking for Ordered List:
a = [ "raju", 21, "k", 2.50, "Rahul", 5, 6 ]
b = [ 12, 32, 16, "l", 6.50, "Rahul", 6 ]
a == b
OUTPUT:
False
CODE EXPLANATION:
This code compares two lists, a and b, using the equality operator ‘==’. The equality operator ‘==’ returns True if the values of the two operands are equal and False otherwise. In this case, the lists a and b contain different elements, so the comparison of a == b will return False.
Although the elements in both lists were the same, the second list changed the fifth element's index position, which went against the lists' intentional order. The comparison between the two lists yields false.
a = [ 11, 22, "Raju", 2.70, "Rakul", 56, 60]
b = [ 11, 22, "Raju", 2.70, "Rakul", 56, 60]
a == b
OUTPUT:
True
CODE EXPLANATION:
This code defines lists a and b and assigns the same values. The expression a == b compares the elements of the two lists and returns a Boolean value of True if all elements of the lists are equal in value and order. So, the result of a == b will be True, indicating that the elements in the two lists are equal.
Lists maintain the order of the elements permanently. This is why it is a planned gathering of things.
CODE:
employee = [ "Jane", 103, "UK"]
department1 = [ "Marketing",20]
department2 = [ "Finance",21]
head_of_department_Marketing = [ 20,"Ms. Smith"]
head_of_department_Finance = [21, "Ms. Johnson"]
print("Printing employee data ...\n")
print("Name : %s, ID: %d, Country: %s\n" %(employee[0], employee[1], employee[2]))
print("Printing departments ...\n")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s\n" %( department1[0], department2[1], department2[0], department2[1]))
print("HOD Details ...\n")
print("Marketing HOD Name: %s, Id: %d\n" %(head_of_department_Marketing[1], head_of_department_Marketing[0]))
print("Finance HOD Name: %s, Id: %d\n" %(head_of_department_Finance[1], head_of_department_Finance[0]))
print(type(employee), type(department1), type(department2), type(head_of_department_Marketing), type(head_of_department_Finance))
OUTPUT:
Printing employee data ...
Name: Jane, ID: 103, Country: UK
Printing departments ...
Department 1:
Name: Marketing, ID: 21
Department 2:
Name: Finance, ID: 21
HOD Details ...
Marketing HOD Name: Ms. Smith, Id: 20
Finance HOD Name: Ms. Johnson, Id: 21
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>
CODE EXPLANATION:
This code is a simple Python program that demonstrates the use of lists and basic string formatting. It contains several lists that store information about an employee, two departments and two heads of departments. The lists contain data such as names, IDs, countries, department names, and heads of department names.
The type function is used to display the type of each of the lists. The code uses the print statement to display this information. The string formatting operator % is used to insert values from the lists into the output string.
Difference Between Set and List:
A Set is a unique list of unordered elements, unlike that is unordered, as opposed to a List, which is an orderly arrangement of elements.