My QA Projects

QA Projects I was involded.

View on GitHub

Sets

documentation

Set have a unique property

Example Set have a unique property

mylist = [1,2,3,3,2,1]
myset = set(mylist)
#passing a sequence as an argument to the set function
print(myset)
# Output
# order of the set may be different on a nother machine or at another time.
{1,2,3}
# Creating a set
animals = {"dog", "cat", "rabbit", "bird", "turtle"}

# Check if an element is in the set
print("cat" in animals)  # Output: True
print("snake" in animals)  # Output: False
# Creating a set
fruits = {"apple", "banana", "cherry", "orange"}

# Using a for loop to iterate over elements in the set
print("Iterating over elements in the set:")
for fruit in fruits:
    print(fruit)
# Using the len() function to get the number of elements in the set
num_fruits = len(fruits)
print("\nNumber of fruits in the set:", num_fruits)

Set literals

set()
#function call

# Creating a set
my_set = {1, 2, 3, 4, 5}
print(my_set)  # Output: {1, 2, 3, 4, 5}

NOTE: it is not using curly braces to represent an empty set. Dictionaries are also using curly braces. => an empty set is relegated to a function call.

#no duplicate items
{-0.5,1,2,3,4,8,16}
{"info@berkeley.edu", "help@irs.gov", "data@wikipedia.com"}
{(10,20), (30,40), (40,30),(20,20)}

Set Functions

Syntax

set(container)

Set Operations

set1 == set2
set1 != set2
item in set2 #membership operator

Compare sets

set1 = {1,2,3,4,4,4,3,3}
print(set1)
# Output => all unique
{1,2,3,4}
set1 = {1,2,3,4,4,4,3,3}
print(set1)
print(set1 == {4,1,2,3})
# compare set1 with values
{1,2,3,4}
True

Set Methods

set.add(item)

s1 = {'a','b','c'}
s1.add('d')
print(s1)
s1.add('a')
print(s1)
#Output
{'a','b','c','d'}
{'a','b','c','d'}
set.remove(item)

s1 = {'a','b','c'}
s1.remove('a')
print(s1)
s1.remove('d')
print(s1)
#Output
{'c','b'}
KeyError:'d'
set.clear()

Set comprehension

Syntax

myset = {exp for item in iteravle if cond_exp}
myset{}
for item in iterable:
    if cond_exp:
        myset.add(exp)  

Example

mylist = [n // 2 for n in range(10)]
print(mylist)
#Output
[0,0,1,1,2,2,3,3,4,4]
mylist = [n // 2 for n in range(10)]
print(mylist)
myset = {n // 2 for n in range(10)}
print(myset)
#Output
[0,0,1,1,2,2,3,3,4,4]
{0,1,2,3,4}
a = {x for x in 'abracadabra' if x not in 'abc'}
a
{'r', 'd'}
Data Type Content Type Sequence Mutable
String characters yes no
list anything yes yes
tubple anything yes no
range integers yes no
set immutable items no yes

back