Knowledge in python tutorial

Change Tuple Values

Change Tuple ValuesOnce a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.ExampleConvert the tuple into a list to be able to change it: x = ("apple", "banana", "cherry")y = list(x)y[1] = "kiwi"x = tuple(y)print(x) Loop Through a TupleYou can loop through the tuple items by using a for loop.ExampleIterate through the items and print the values: thistuple = ("apple", "banana", "cherry") for x in thistuple: print(x) You will learn more about for loops in our Python For Loops Chapter.Check if Item ExistsTo determine if a specified item is present in a tuple use the in keyword:ExampleCheck if "apple" is present in the tuple: thistuple = ("apple", "banana", "cherry") if "apple" in thistuple: print("Yes, 'apple' is in the fruits tuple") Tuple LengthTo determine how many items a tuple has, use the len() method:ExamplePrint the number of items in the tuple: thistuple = ("apple", "banana", "cherry") print(len(thistuple))

Python Sets

Python SetsSetA set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.ExampleCreate a Set: thisset = {"apple", "banana", "cherry"}print(thisset) Note: Sets are unordered, so you cannot be sure in which order the items will appear.Access ItemsYou cannot access items in a set by referring to an index, since sets are unordered the items has no index.But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.ExampleLoop through the set, and print the values: thisset = {"apple", "banana", "cherry"}for x in thisset: print(x) ExampleCheck if "banana" is present in the set: thisset = {"apple", "banana", "cherry"}print("banana" in thisset)

Change Items

Change ItemsOnce a set is created, you cannot change its items, but you can add new items.Add ItemsTo add one item to a set use the add() method.To add more than one item to a set use the update() method.ExampleAdd an item to a set, using the add() method: thisset = {"apple", "banana", "cherry"} thisset.add("orange")print(thisset) ExampleAdd multiple items to a set, using the update() method: thisset = {"apple", "banana", "cherry"}thisset.update(["orange", "mango", "grapes"])print(thisset)

Get the Length of a Set

Get the Length of a SetTo determine how many items a set has, use the len() method.ExampleGet the number of items in a set: thisset = {"apple", "banana", "cherry"} print(len(thisset)) Remove ItemTo remove an item in a set, use the remove(), or the discard() method.ExampleRemove "banana" by using the remove() method: thisset = {"apple", "banana", "cherry"} thisset.remove("banana") print(thisset) Note: If the item to remove does not exist, remove() will raise an error.ExampleRemove "banana" by using the discard() method: thisset = {"apple", "banana", "cherry"} thisset.discard("banana") print(thisset)

Join Two Sets

Join Two SetsThere are several ways to join two or more sets in Python.You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:ExampleThe union() method returns a new set with all items from both sets: set1 = {"a", "b" , "c"}set2 = {1, 2, 3} set3 = set1.union(set2)print(set3) ExampleThe update() method inserts the items in set2 into set1: set1 = {"a", "b" , "c"}set2 = {1, 2, 3} set1.update(set2)print(set1)

Python Dictionaries

Python DictionariesDictionaryA dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.ExampleCreate and print a dictionary: thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 } print(thisdict) Accessing ItemsYou can access the items of a dictionary by referring to its key name, inside square brackets:ExampleGet the value of the "model" key: x = thisdict["model"] There is also a method called get() that will give you the same result:ExampleGet the value of the "model" key: x = thisdict.get("model")

Change Values

Change ValuesYou can change the value of a specific item by referring to its key name:ExampleChange the "year" to 2018: thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 }thisdict["year"] = 2018 Loop Through a DictionaryYou can loop through a dictionary by using a for loop.When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.ExamplePrint all key names in the dictionary, one by one: for x in thisdict: print(x) ExamplePrint all values in the dictionary, one by one: for x in thisdict: print(thisdict[x]) ExampleYou can also use the values() function to return values of a dictionary: for x in thisdict.values(): print(x) ExampleLoop through both keys and values, by using the items() function: for x, y in thisdict.items(): print(x, y)

Check if Key Exists

Check if Key ExistsTo determine if a specified key is present in a dictionary use the in keyword:ExampleCheck if "model" is present in the dictionary: thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 } if "model" in thisdict: print("Yes, 'model' is one of the keys in the thisdict dictionary") Dictionary LengthTo determine how many items (key-value pairs) a dictionary has, use the len() method.ExamplePrint the number of items in the dictionary: print(len(thisdict)) Adding ItemsAdding an item to the dictionary is done by using a new index key and assigning a value to it:Example thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 }thisdict["color"] = "red"print(thisdict)

Removing Items

Removing ItemsThere are several methods to remove items from a dictionary:ExampleThe pop() method removes the item with the specified key name: thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 }thisdict.pop("model") print(thisdict) ExampleThe popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead): thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 }thisdict.popitem() print(thisdict) ExampleThe del keyword removes the item with the specified key name: thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 }del thisdict["model"]print(thisdict) ExampleThe del keyword can also delete the dictionary completely: thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 }del thisdictprint(thisdict) #this will cause an error because "thisdict" no longer exists.

Copy a Dictionary

Copy a DictionaryYou cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.There are ways to make a copy, one way is to use the built-in Dictionary method copy().ExampleMake a copy of a dictionary with the copy() method: thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 }mydict = thisdict.copy() print(mydict) Another way to make a copy is to use the built-in method dict().ExampleMake a copy of a dictionary with the dict() method: thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 }mydict = dict(thisdict) print(mydict)

Nested Dictionaries

Nested DictionariesA dictionary can also contain many dictionaries, this is called nested dictionaries.ExampleCreate a dictionary that contain three dictionaries: myfamily = { "child1" : {   "name" : "Emil",    "year" : 2004 }, "child2" : {    "name" : "Tobias",   "year" : 2007 },  "child3" : {   "name" : "Linus",    "year" : 2011 }} Or, if you want to nest three dictionaries that already exists as dictionaries:ExampleCreate three dictionaries, than create one dictionary that will contain the other three dictionaries: child1 = { "name" : "Emil", "year" : 2004}child2 = {  "name" : "Tobias", "year" : 2007}child3 = { "name" : "Linus",  "year" : 2011}myfamily = { "child1" : child1,  "child2" : child2, "child3" : child3}

The dict() Constructor

The dict() ConstructorIt is also possible to use the dict() constructor to make a new dictionary:Example thisdict = dict(brand="Ford", model="Mustang", year=1964) # note that keywords are not string literals # note the use of equals rather than colon for the assignment print(thisdict)