User Tools

Site Tools


products:ict:python:sets_questions

Q: What is a set in Python? A: A set is an unordered collection of unique elements in Python.

Q: How do you create an empty set in Python? A: You can create an empty set using the set() function.

Q: How do you create a set with elements in Python? A: You can create a set by enclosing the elements within curly braces {} or by using the set() function with a sequence.

Q: Can a set contain duplicate elements? A: No, a set cannot contain duplicate elements. It only stores unique values.

Q: How do you add elements to a set? A: You can add elements to a set using the add() method.

Q: How do you remove elements from a set? A: You can remove elements from a set using the remove() or discard() method.

Q: How do you check if an element exists in a set? A: You can use the “in” keyword to check if an element exists in a set.

Q: How do you find the length of a set? A: You can use the len() function to find the length of a set.

Q: Can you access elements of a set by index? A: No, sets are unordered collections, so you cannot access elements by index.

Q: Can you change elements of a set? A: No, sets are mutable, but the elements themselves are immutable. You can only add or remove elements.

Q: How do you perform union operation on two sets? A: You can use the union() method or the “|” operator to perform the union operation on two sets.

Q: How do you perform intersection operation on two sets? A: You can use the intersection() method or the “&” operator to perform the intersection operation on two sets.

Q: How do you perform difference operation on two sets? A: You can use the difference() method or the “-” operator to perform the difference operation on two sets.

Q: How do you perform symmetric difference operation on two sets? A: You can use the symmetric_difference() method or the “^” operator to perform the symmetric difference operation on two sets.

Q: Can you sort a set in Python? A: No, sets are unordered collections, so you cannot sort them. If you need a sorted collection, you can convert the set to a list and then sort the list.

Q: Can a set contain a list as an element? A: No, sets can only contain immutable elements. Lists are mutable, so they cannot be elements of a set. However, you can convert the list to a tuple and then add it to a set.

Q: How do you clear all elements from a set? A: You can use the clear() method to remove all elements from a set.

Q: Can you create a set of sets in Python? A: No, sets cannot contain mutable elements, so you cannot have a set of sets. However, you can have a set of tuples, where each tuple represents a set.

Q: Can you convert a list to a set in Python? A: Yes, you can convert a list to a set using the set() function.

Q: Can you convert a set to a list in Python? A: Yes, you can convert a set to a list using the list() function.

products/ict/python/sets_questions.txt · Last modified: 2023/05/06 16:47 by wikiadmin