Python Built-In Datastructures : List,Tuples, Dictionaries & Strings#

Basic Structure - Properties - Creating - Accessing - Modifiying (Adding, Updating, rearranging) - Deleting - Type Conversion - Operations with dictionary - Useful Cases examples

List#

  • Properties

    • Mutable

  • Creating

  • Accessing

    • l.pop() -> return last element

  • Modifiying (Adding, Updating, rearranging)

    • Append(Only appends one elemet at a time)

    • Insert

    • Extend(Only accepts iterable)

  • Deleting

  • Type Conversion

  • Operations with dictionary

  • Useful Cases examples

Modifying#

[4]:
'''
You can add elements to the end of a list,
or you can insert them wherever you like
in a list
'''
users = ['vale','bob','mia','ron','ned']
users2 = ['yes','no']
#Append
users.append('sandy')
#Insert
users.insert(0,'nayak')
#Extend
users.extend(users2)

print(users)
['nayak', 'vale', 'bob', 'mia', 'ron', 'ned', 'sandy', 'yes', 'no']

Deleting#

[8]:
#removing
users = ['nayak','vale','bob','mia','ron','ned','sandy']

#remove nayak
#output : ['vale', 'bob', 'mia', 'ron', 'ned', 'sandy']
users.remove('nayak')

#remove 'sandy' and return it
#output:['vale', 'bob', 'mia', 'ron', 'ned']
users.pop()

#clear users list
users.clear()
users
[8]:
[]

Useful Cases examples#

[9]:
#Getting Index
users = ['nayak','vale','bob','sandy','mia','ron','ned','sandy']

#return index of 'sandy'
#output: 3
users.index('sandy')

#return count of 'sandy'
#output:2
users.count('sandy')
[9]:
2
[14]:
'''The sort() method changes the order of a list
permanently. The sorted() function returns
a copy of the list, leaving the original list
unchanged. You can sort the items in a list in
alphabetical order, or reverse alphabetical
order. You can also reverse the original order of
the list. Keep in mind that lowercase and uppercase
letters may affect the sort order'''
users = ['a','A','b','B','c','d','e']

#Sorting in reverse alphabetical order & guess its output
users.sort(reverse=True)
print(users)

#Do a temp. sorting but do not change list
print(sorted(users)) #does not affect users, returns a copy
print(users)
users.reverse() # returns none.


# You might have noticed that methods like insert, remove or sort that only modify the
# list have no return value printed they return the default None.
# This is a design principle for all mutable data structures in Python.
# The list.sort() method returns None.
# The list.reverse() method returns None.
# The list.append() method returns None.

['e', 'd', 'c', 'b', 'a', 'B', 'A']
['A', 'B', 'a', 'b', 'c', 'd', 'e']
['e', 'd', 'c', 'b', 'a', 'B', 'A']

Dictionaries#

  • Properties

    1. keys: Immutable Objects like Strings, numbers

    2. keys: tuples can be used as keys if it contains only immutables like strings/ numbers. But,if it contains,lets say list, cannot

    3. keys: lists cannot be used since it is mutable.

  • Creating

    1. {key:value} -> Dictionary

    2. dict() -> New Dictonary

    3. dict.fromkeys(s) -> New dictionary with the given sequence of elements as the keys of the dictionary

    4. dict_comprehension -> {key:value for key,value in zip(keys,value)})

  • Accessing

    1. d[key] ->Value

    2. d.get(key) -> Value [Useful as instead of Errors, I can return default values]

    3. d.keys() -> Iterable of keys

    4. d.values() -> Iterable of values

    5. d.items() -> Iterable of items -> keys,values

    6. d.setdefault() -> Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

  • Modifiying (Adding, Updating, rearranging)

    1. d[key] = value

    2. d.update(d2) or d.update({key:value}) -> Updated d with d2 added to d dictionary

  • Deleting

    1. d.pop(key) -> Returns the value & Removes the element with the key (can take key as argument. )

    2. d.popitem() -> Returns tuple of last (key,value) & Removes the last inserted key-value pair

    3. d.del[key] -> Remove individual items

    4. d.clear() -> Return empty dict & Removes the entire dictionay

  • Type Conversion

  • Operations with dictionary

  • Useful Cases examples

Creating#

[15]:
#The dict() constructor builds dictionaries directly from sequences of key-value pairs

dict1=dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) # list of Tuples
print(dict1)
dict2=dict([['sape', 4139], ['guido', 4127],['jack', 4098]]) # List of list
print(dict2)
dict3=dict((('sape', 4139), ('guido', 4127),('jack', 4098))) # Tuple of tuple
print(dict3)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
{'sape': 4139, 'guido': 4127, 'jack': 4098}
{'sape': 4139, 'guido': 4127, 'jack': 4098}
[ ]:
#dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:
print({x:x**2 for x in (2,4,6)})
keys = [key for key in 'sandeep']
value = [value for value in range(len('sandeep'))]
print(keys)
print(value)
print({key:value for key,value in zip(keys,value)})
[16]:
#When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
print(dict(sape=4139, guido=4127, jack=4098))
# print(dict(1=4139, 2=4127, 3=4098)) # This will produce error!
{'sape': 4139, 'guido': 4127, 'jack': 4098}
[17]:
#dict.fromkeys(sequence[,value])
tuple1 = ('app','mobile','electricity')
d = dict.fromkeys(tuple1); print(d)

value = [2]
d = dict.fromkeys(tuple1,value); print(d)

value.append(3);print(d)  # appending the list appends the new dictionary also !
# each element is assigned a reference to the same object (points to the same object in the memory).

#Using dictionary comprehension to solve the above problem.
tuple1 = ('app','mobile','electricity')
value = [2]
d2 = {key:list(value) for key in tuple1}; print(d2) # Here list(value), making a list is important.
value.append(3);print(d2)

{'app': None, 'mobile': None, 'electricity': None}
{'app': [2], 'mobile': [2], 'electricity': [2]}
{'app': [2, 3], 'mobile': [2, 3], 'electricity': [2, 3]}
{'app': [2], 'mobile': [2], 'electricity': [2]}
{'app': [2], 'mobile': [2], 'electricity': [2]}

Accessing#

[19]:
d  = {"apple" : 5, "pear" : 3, "banana" : 4, "pineapple" : 1, "cherry" : 20}
# Accessing using []
print(d["pineapple"])
# Using keys to get iterator of key.
print(d.keys())
print([key for key in d.keys()])
# Using values to get iterator of values.
print(d.values())
print([value for value in d.values()])
# Using items to get iterator of key-value pairs.
print(d.items())
print([item for item in d.items()])
# Using get to get the value of a key.
# If the key is not present, get returns default:None, no erros.
print(d.get('cherry',None))
# Using setdefault to get the value of a key.
# If the key is not present, setdefault adds the key-value pair and returns the value.
print(d.setdefault('apple'))
print(d.setdefault('orange',9))
print(d)


1
dict_keys(['apple', 'pear', 'banana', 'pineapple', 'cherry'])
['apple', 'pear', 'banana', 'pineapple', 'cherry']
dict_values([5, 3, 4, 1, 20])
[5, 3, 4, 1, 20]
dict_items([('apple', 5), ('pear', 3), ('banana', 4), ('pineapple', 1), ('cherry', 20)])
[('apple', 5), ('pear', 3), ('banana', 4), ('pineapple', 1), ('cherry', 20)]
20
5
9
{'apple': 5, 'pear': 3, 'banana': 4, 'pineapple': 1, 'cherry': 20, 'orange': 9}

Modifiying (Adding, Updating, rearranging)#

[20]:
d  = {"apple" : 5, "pear" : 3, "banana" : 4, "pineapple" : 1, "cherry" : 20}
# If organe not there, organe will get added.
d["orange"] = 19
print(d)
# Update takes in iterable.
d.update({'mango':29})
print(d)
# d.update() also takes a dictionary.
car = {  "brand": "Ford", "model": "Mustang",  "year": 1964}
d.update(car)
print(d)
{'apple': 5, 'pear': 3, 'banana': 4, 'pineapple': 1, 'cherry': 20, 'orange': 19}
{'apple': 5, 'pear': 3, 'banana': 4, 'pineapple': 1, 'cherry': 20, 'orange': 19, 'mango': 29}
{'apple': 5, 'pear': 3, 'banana': 4, 'pineapple': 1, 'cherry': 20, 'orange': 19, 'mango': 29, 'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Deleting#

  1. d.pop(key) -> Returns the value & Removes the element with the key (can take key as argument. )

  2. d.popitem() -> Returns tuple of last (key,value) & Removes the last inserted key-value pair(Does not take arguments)

  3. d.del[key] -> Remove individual items

  4. d.clear() -> Return empty dict & Removes the entire dictionay

[21]:
d  = {"apple" : 5, "pear" : 3, "banana" : 4, "pineapple" : 1, "cherry" : 20}
#pop(), popitem()
print(d.pop('apple'));print(d)
print(d.popitem());print(d)

#del
del d["pear"];print(d)

d.clear() ; print(d)

del d ; # Delets the variable itself.
5
{'pear': 3, 'banana': 4, 'pineapple': 1, 'cherry': 20}
('cherry', 20)
{'pear': 3, 'banana': 4, 'pineapple': 1}
{'banana': 4, 'pineapple': 1}
{}

Strings#

Properties#

  1. Immutable

  2. All characters are string in python

Accessing#

  • Just like lists

[23]:
var1 = 'Hello World!'
print(var1[0:2])
String1 = "GeeksForGeeks"
# "Slicing characters betwee 3rd and 2nd last character: ")
print(String1[3:-2])
He
ksForGee

Delete/ Updating#

  • can update the entire string by variable assignment

  • can delete the entire string by usign del keyword

[24]:
string1= 'A'
del string1
# print(string1) #  NameError: name 'string1' is not defined

Useful Cases examples#

Raw Strings#

[25]:
string2 = 'C:\\Python\\Geeks\\'
#To ignore the escape sequences in a String, r or R is used,
#this implies that the string is a raw string and escape sequences inside it are to be ignored.
string3 = r'C:\\Python\\Geeks\\'
print(string2)
print(string3)
C:\Python\Geeks\
C:\\Python\\Geeks\\

Triple Quotes#

  • Spanning strings over multiple lines can be done using python’s triple quotes. It can also be used for long comments in code. Special characters like TABs, verbatim or NEWLINEs can also be used within the triple quotes

  • Triple quotes, according to official Python documentation are docstrings, or multi-line docstrings and are not considered comments.

[27]:
# Can only be a single line, else error!
string4 = "sandeep nayak is a good boy"
# If you want to add multi-line strings, use 3 double quotes: """
string5 = """hi ,
this is
sandeep"""
print(string5)
hi ,
this is
sandeep

Operators in Strings#

[28]:
a = "Hello"
b = "Python"
# Concatenate
print(a+b)
# Repeat
print(a*4)
# Indexing
print(a[0])
# Slicing
print(a[3:-1])
# Elements in
print("H" in a)
print("H" not in a)
HelloPython
HelloHelloHelloHello
H
l
True
False

String Methods#

s.startswith(str, beg=0,end=len(string))#
[29]:
"""
s.startswith(str, beg=0,end=len(string))
Returns:
    True/ False

str − This is the string to be checked.
beg − This is the optional parameter to set start index of the matching boundary.
end − This is the optional parameter to end start index of the matching boundary.
"""
s = "this is live code relive"
print(s.startswith('this'))
print(s.startswith('th'))
print(s.startswith('this is live'))
print(s.startswith( 'live', 8, 12 ))#str.startswith(str, beg=0,end=len(string))
print(s.startswith( 'this', 8, 12 ))
True
True
True
True
False

s.endswith(suffix[, start[, end]])

[30]:
# s.endswith(suffix[, start[, end]])

str = "this is string example....wow!!!"
suffix = "wow!!!"
print(str.endswith(suffix))
print(str.endswith(suffix,20)) # start, slice begin from here,it sees [ample....wow!!!]
suffix = "is";
print(str.endswith(suffix, 2, 4))
print(str.endswith(suffix, 2, 6))
True
True
True
False
s.count(str, beg= 0,end=len(string))#
[31]:
"""
s.count(str, beg= 0,end=len(string))
returns: count : int
Counts how many times non-overlapping! str occurs in string or in a substring
of string if starting index beg and ending index end are given.
"""
str = "this is string example....wowwowwow!!!"
sub = "i"
print(f"str.count({sub}) : ", str.count(sub, 4, 15))
# Example for non-overlapping count!
sub = "wow"
print(f"str.count({sub}) : ", str.count(sub))
str.count(i) :  2
str.count(wow) :  3
s.strip()#
[ ]:
"""
s.strip()
returns:returns a copy of the string in which all
chars have been stripped from the beginning and
the end of the string (default whitespace characters).
"""
str = "0000000this is string example....wow!!!0000000";
print(str.strip( '0' ))
# print(str.strip( ['0','i'] )) #TypeError: strip arg must be None or str
# print(str.strip('0','i')) #TypeError: strip() takes at most 1 argument (2 given)
s.partition(sep)#
[33]:
"""
s.partition(sep) -> (before, sep, after)
returns:
    3-tuple containing:(before, sep, after)

-the part before the separator, separator parameter,
and the part after the separator if the separator parameter is found in the string

-string itself and two empty strings if the separator parameter is not found
"""

string = "Python is fun"
# 'is' separator is found
print(string.partition('is '))
# 'not' separator is not found
print(string.partition('not '))
string = "Python is fun, is n't it"
# splits at first occurence of 'is'
print(string.partition('is'))
('Python ', 'is ', 'fun')
('Python is fun', '', '')
('Python ', 'is', " fun, is n't it")
s.split([separator [, maxsplit]])#
[35]:
"""
s.split([separator [, maxsplit]]) ->  list of strings split wtr [seq]

-separator (optional)- The is a delimiter. The string splits at the specified separator.
If the separator is not specified, any whitespace (space, newline etc.) string is a separator.
-maxsplit (optional) - The maxsplit defines the maximum number of splits.
The default value of maxsplit is -1, meaning, no limit on the number of splits.

The split() breaks the string at the separator and returns a list of strings.

"""
grocery = 'Milk, Chicken, Bread'

# splits at ','
print(grocery.split(', '))
# Splitting at ':'
print(grocery.split(':'))
# maxsplit: 1
print(grocery.split(', ', 1))
# maxsplit: 5
print(grocery.split(', ', 5))
# maxsplit: 0
print(grocery.split(', ', 0))
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']
['Milk', 'Chicken, Bread']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']
s.join(iterable)#
[36]:
"""
s.join(iterable) -> Takes s and concatinate it to elements of iterable
Some of the example of iterables are:

Native datatypes - List, Tuple, String, Dictionary and Set
File objects and objects you define with an __iter__() or __getitem()__ method

Errors:
iterable contains any non-string values, it raises a TypeError exception.

"""
numList = ['1', '2', '3', '4']
seperator = ', '
print(seperator.join(numList))

numTuple = ('1', '2', '3', '4')
print(seperator.join(numTuple))

s1 = 'abc'
s2 = '123'

""" Each character of s2 is concatenated to the front of s1"""
print( s1.join(s2))

""" Each character of s1 is concatenated to the front of s2"""
print( s2.join(s1))

test = {'Python', 'Java', 'Ruby'} # (Set)
s = '->->'
print(s.join(test))

test =  {'mat': 1, 'that': 2}
s = '->'
print(s.join(test))

test =  {1:'mat', 2:'that'} # Error, int found.
s = ', '

# this gives error:iterable contains any non-string values, it raises a TypeError exception.
print(s.join(test))
1, 2, 3, 4
1, 2, 3, 4
1abc2abc3
a123b123c
Ruby->->Java->->Python
mat->that
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_102465/463981995.py in <module>
     38
     39 # this gives error:iterable contains any non-string values, it raises a TypeError exception.
---> 40 print(s.join(test))

TypeError: sequence item 0: expected str instance, int found
s.index(sub[, start[, end]] )#
[37]:
"""
s.index(sub[, start[, end]] )
    sub - substring to be searched in the string str.
    start and end(optional) - substring is searched within str[start:end]

Returns:
    -If substring exists inside the string, it returns the lowest
     index in the string where substring is found.
    -If substring doesn't exist inside the string, it raises a ValueError exception.
The index() method is similar to find() method for strings.
The only difference is that find() method returns -1 if
the substring is not found, whereas index() throws an exception.

"""
sentence = 'Python programming is fun to be is fun'
result = sentence.index('is fun')
print("Substring 'is fun':", result)
result = sentence.index('Java')
print("Substring 'Java':", result)
Substring 'is fun': 19
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_102465/188644721.py in <module>
     16 result = sentence.index('is fun')
     17 print("Substring 'is fun':", result)
---> 18 result = sentence.index('Java')
     19 print("Substring 'Java':", result)

ValueError: substring not found
s.find(sub[, start[, end]] )#
[38]:
"""
s.find(sub[, start[, end]] )
    sub - It's the substring to be searched in the str string.
    start and end (optional) - substring is searched within str[start:end]
Returns:
    find() method returns an integer value.
    -If substring exists inside the string, it returns the index of first occurence of the substring.
    -If substring doesn't exist inside the string, it returns -1.


"""
quote = 'Let it be, let it be, let it be'

result = quote.find('let it')
print("Substring 'let it':", result)

result = quote.find('small')
print("Substring 'small ':", result)

# How to use find()
if  (quote.find('be,') != -1): # ie. it contains 'be'
  print("Contains substring 'be,'")
else:
  print("Doesn't contain substring")
Substring 'let it': 11
Substring 'small ': -1
Contains substring 'be,'
String Checker s.is<alpha…>#

s.isalnum()

s.isalpha()

s.isdecimal()

s.isdigit()

s.isidentifier()

s.islower()

s.isnumeric()

s.isprintable()

s.isspace()

s.istitle()

s.isupper()

[51]:
""" s.is ... -> True/False

Python String isalnum()
Python String isalpha()
Python String isdecimal()
Python String isdigit()
Python String isidentifier()
Python String islower()
Python String isnumeric()
Python String isprintable()
Python String isspace()
Python String istitle()
Python String isupper()

"""
# Checks for contains whitespace/other characters that are not alpha-numeric
name = "M3onica Gell22er "
if name.isalnum() == True:
   print("All characters of string (name) are alphanumeric.")
else:
    print("All characters are not alphanumeric.")
# contains alphabets and spaces
print(f'{name} => isalpha:{name.isalpha()}')

name = "Mo3 nicaG el l22er"
print(f'{name} => isdecimal:{name.isdecimal()}')

name = 'str'
print(f'{name} => isidentifier:{name.isidentifier()}')

name = 'th!s is a1so g00d'
print(f'{name} => islower:{name.islower()}')

name = "THIS IS ALSO G00D!"
print(f'{name} => isupper:{name.isupper()}')

"""
s.isnumeric()
    Return: True/False
A numeric character has following properties:

Numeric_Type=Decimal
Numeric_Type=Digit
Numeric_Type=Numeric
In Python, decimal characters (like: 0, 1, 2..),
digits (like: subscript, superscript),
and characters having Unicode numeric value property
(like: fraction, roman numerals, currency numerators) are all considered numeric characters.

"""
# s = '½'
name = '\u00BD'
print(f'{name} => isnumeric:{name.isnumeric()}')
All characters are not alphanumeric.
M3onica Gell22er  => isalpha:False
Mo3 nicaG el l22er => isdecimal:False
str => isidentifier:True
th!s is a1so g00d => islower:True
THIS IS ALSO G00D! => isupper:True
½ => isnumeric:True
String Convertor#

s.upper()

s.lower()

s.title() -> copy of the string in which first characters of all the words are capitalized

s.swapcase() ->copy of the string in which all the case-based characters have had their case swapped.

s.casefold() -> doing a case-insensitive string comparison, Consider Unicode Normalization

s.capitalize()

[53]:
"""
s.upper(), s.lower(),

s.title() -> copy of the string in which first characters of all the words are capitalized.

s.swapcase() ->copy of the string in which all the case-based characters have had their case swapped.

s.casefold() -> doing a case-insensitive string comparison, Consider Unicode Normalization

s.capitalize() -> Capitalizes


"""
string = "Th!s Sh0uLd B3 uPp3rCas3!"
print(string.upper())

str = "this is string example....wow!!!";
print(str.title())

str = "this is string example....wow!!!";
print(str.capitalize())

str = "THIS is string example....wow!!!";
print(str.swapcase())

# CASEFOLDING better thean s.lower() for unicode normalization comparison.
firstString = "der Fluß" # Unicoode B is equal to lower case ss.
secondString = "der Fluss"

# ß is equivalent to ss
if firstString.casefold() == secondString.casefold():
    print('The strings are equal.')
else:
    print('The strings are not equal.')
TH!S SH0ULD B3 UPP3RCAS3!
This Is String Example....Wow!!!
This is string example....wow!!!
this IS STRING EXAMPLE....WOW!!!
The strings are equal.
String Padding#

s.center(width[, fillchar])

s.rjust(width[, fillchar])

s.ljust(width[, fillchar])

s.zfill(width)

[54]:
"""
s.center(width[, fillchar]) -> string which is padded with the specified character.

s.rjust(width[, fillchar]) -> right-justified string of a given minimum width

s.ljust(width[, fillchar]) -> left-justified string of a given minimum width.

"""
string = "Python is awesome"
new_string = string.center(22, '*')
print("Centered String: ", new_string)

# example string
string = 'cat'
width = 5
fillchar = '*'
# print right justified string
print(string.rjust(width, fillchar))
# he minimum width defined is 5. So, the resultant string is atleast of length 5.
#Now, rjust() aligns the string 'cat' to the right leaving two spaces to the left of the word
print(string.ljust(width, fillchar))
# s.zfill(width) -> string from zfill() with '0' digits filled to the left
number = "-290"
print(number.zfill(8))
Centered String:  **Python is awesome***
**cat
cat**
-0000290

Sets#

  • Properties

    1. set elements: Has unique & must be immutable ie.A set cannot have mutable elements like a list, set or dictionary, as its elements.

    2. However, the set itself is mutable. We can add or remove items from it.

    3. set: unordered , so indexing has no meaning.

    4. forzenset() -> immutable set, so no adding/removing operations. rest: same as set.

  • Creating

    1. {value1,value2} -> set in curly brackets separated by comma

    2. set() -> create set, accepts immutables

  • Accessing

    1. unordered, so cannot access elements. Instead use membership tests.

  • Modifiying (Adding, Updating, rearranging)

    1. s.add() -> Adds an element to the set

    2. s.update -> Only takes iterable. Adds all elements to the set by updating it.

  • Deleting

    1. s.pop() -> !! It does not take any values!! Returns random item & remove it from set

    2. s.remove(key) -> remove the particular key from set. Raises Error if key does not exist.

    3. s.discard(key) -> remove the particular key from set. Does not raise error if key does not exists.

    4. s.clear() -> clears the entire set.

  • Type Conversion

    1. set() -> create set, accepts immutables

  • Operations with set

Basic Mathematical Operations : operators or methods available.

  1. or union() -> set of A union B
  2. & or intersection() -> set of A intersection B

    • or difference () -> set of elements only in A for A-B or only in B for B-A

  3. ^ or symmetric_difference() -> set of elements only in A + only in B

  4. <= or s.issubset(t) -> Returns True if s issubset(t) ie. all elements in s are in t

  5. >= or s.issuperset(t) -> Returns True if s issuperset(t) ie. all elements in t is in s.

  6. s.intersection_update(t) -> return set s ie. update s keeping only elements also found in t. !! makes direct change to set s.

  7. s.difference_update(t) -> return set s after removing elements found in t

  8. s.symmetric_difference_update(t) -> return set s with elements from s or t but not both

  9. s.isdisjoint(t) -> Returns true if there is no intersection

  10. key in s, key not in s -> Return true if a key in s.

  • Useful Cases examples

    1. Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.

Creating#

  1. {value1,value2} -> set in curly brackets separated by comma

  2. set() -> create set, accepts immutables

[55]:
s = {1.0,'hello',(1,2,3)};print(s)
s2 = set([1,2,3,4]) ;print(s2) # set from dict
{1.0, 'hello', (1, 2, 3)}
{1, 2, 3, 4}

Modifiying (Adding, Updating, rearranging)#

  1. s.add() -> Adds an element to the set

  2. s.update(iterable) -> Only takes iterable. Adds all elements to the set by updating it.

[56]:
#Adding
like = ["I","like"," Robotics and computer Science","thank","geeks","for","geeks"]
set_like = set(like);print(set_like)
# s.add(elem)->Add an element to a set
set_like.add("sandy");print(set_like)
# s.update(iterable)->Add multiple elements to a set

list1 = ['lst1','lst2'] #list
tuple1 = ("tuple1","tuple2")
set1 =  {'set1','set2'}

set_like.update(list1,tuple1,set1); print(set_like)
# update() only works for iterable objects
set_like.update([2]);print(set_like)
#set_like.update(2);print(set_like) # Error:'int' object is not iterable
# set_like.update(["using","update",[1,2,3,4]]) # Error: unhashable type: 'list'
{'I', ' Robotics and computer Science', 'for', 'like', 'thank', 'geeks'}
{'I', ' Robotics and computer Science', 'for', 'like', 'thank', 'sandy', 'geeks'}
{'I', ' Robotics and computer Science', 'for', 'like', 'thank', 'set2', 'set1', 'tuple1', 'lst2', 'tuple2', 'sandy', 'lst1', 'geeks'}
{'I', 2, ' Robotics and computer Science', 'for', 'like', 'thank', 'set2', 'set1', 'tuple1', 'lst2', 'tuple2', 'sandy', 'lst1', 'geeks'}

Deleting#

  1. s.pop() -> !! It does not take any values!! Returns random item & remove it from set

  2. s.remove(key) -> remove the particular key from set. Raises Error if key does not exist.

  3. s.discard(key) -> remove the particular key from set. Does not raise error if key does not exists.

  4. s.clear() -> clears the entire set.

[57]:
# 1. s.pop() -> !! It does not take any values!!  Returns random item & remove it from set
s={'apple','orange','mango'}
print(s.pop());print(s)
# print(s.pop('apple'));print(s) #Error: pop does not take arguments.

# 2. s.remove(key) ->  remove the particular key from set. Raises Error if key does not exist.
s={'apple','orange','mango'}
s.remove('apple');print(s)
# s.remove('sandy') # keyerror: 'sandy'

# 3. s.discard(key) -> remove the particular key from set. Does not raise error if key does not exists.
s = {'apple','orange','mango'}
s.discard('apple');print(s)
# s.discard('sandy') # No errors.

# 4. s.clear() -> clears the entire set.
s = {'apple','orange','mango'}
s.clear();print(s)
apple
{'mango', 'orange'}
{'mango', 'orange'}
{'mango', 'orange'}
set()

Operations with set#

Basic Mathematical Operations : operators or methods available.

1. | or union() -> set of  A union B
2. & or intersection() -> set of A intersection B
3. \- or difference () -> set of elements only in A for A-B or only in B for B-A
4. ^ or symmetric_difference() -> set of elements only in A + only in B
5. <= or s.issubset(t) -> Returns True if s issubset(t) ie. all elements in s are in t
6. \>= or s.issuperset(t) -> Returns True if s issuperset(t) ie. all elements in t is in s.
7. s.intersection_update(t) -> return set s ie. update s keeping only elements also found in t. !! makes direct change to set s.
8. s.difference_update(t) -> return set s after removing elements found in t
9. s.symmetric_difference_update(t) -> return set s with elements from s or t but not both
10. s.isdisjoint(t) -> Returns true if there is no intersection
11. key in s, key not in s -> Return true if a key in s.
[61]:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# | or union() -> set of  A union B
print(A|B)
print(A.union(B))

# & or intersection() -> set of A intersection B
print(A&B)
print(A.intersection(B))

# - or difference () -> set of elements only in A for A-B or only in B for B-A
print(A-B); print(A.difference(B))
print(B-A); print(B.difference(A))

# ^ or symmetric_difference() -> set of elements only in A + only in B
print(A^B) ; print(A.symmetric_difference(B))
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{4, 5}
{1, 2, 3}
{1, 2, 3}
{8, 6, 7}
{8, 6, 7}
{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}