Knowledge in Python

Copy a List

Copy a ListYou cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.There are ways to make a copy, one way is to use the built-in List method copy().ExampleMake a copy of a list with the copy() method: thislist = ["apple", "banana", "cherry"]mylist = thislist.copy() print(mylist) Another way to make a copy is to use the built-in method list().ExampleMake a copy of a list with the list() method: thislist = ["apple", "banana", "cherry"]mylist = list(thislist) print(mylist) Join Two ListsThere are several ways to join, or concatenate, two or more lists in Python.One of the easiest ways are by using the + operator.ExampleJoin two list: list1 = ["a", "b" , "c"]list2 = [1, 2, 3]list3 = list1 + list2 print(list3) Another way to join two lists are by appending all the items from list2 into list1, one by one:ExampleAppend list2 into list1: list1 = ["a", "b" , "c"]list2 = [1, 2, 3] for x in list2: list1.append(x)print(list1)

Python Tuples

Python TuplesTupleA tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.ExampleCreate a Tuple: thistuple = ("apple", "banana", "cherry") print(thistuple) Access Tuple ItemsYou can access tuple items by referring to the index number, inside square brackets:ExamplePrint the second item in the tuple: thistuple = ("apple", "banana", "cherry") print(thistuple[1])

Negative Indexing

Negative IndexingNegative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.ExamplePrint the last item of the tuple: thistuple = ("apple", "banana", "cherry") print(thistuple[-1]) Range of IndexesYou can specify a range of indexes by specifying where to start and where to end the range.When specifying a range, the return value will be a new tuple with the specified items.ExampleReturn the third, fourth, and fifth item: thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[2:5])

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))

Create Tuple With One Item

Add ItemsOnce a tuple is created, you cannot add items to it. Tuples are unchangeable.ExampleYou cannot add items to a tuple: thistuple = ("apple", "banana", "cherry") thistuple[3] = "orange" # This will raise an errorprint(thistuple) Create Tuple With One ItemTo create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.ExampleOne item tuple, remember the commma: thistuple = ("apple",) print(type(thistuple))#NOT a tuplethistuple = ("apple") print(type(thistuple)) Remove ItemsNote: You cannot remove items in a tuple. Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:ExampleThe del keyword can delete the tuple completely: thistuple = ("apple", "banana", "cherry") del thistupleprint(thistuple) #this will raise an error because the tuple no longer exists Join Two TuplesTo join two or more tuples you can use the + operator:ExampleJoin two tuples: tuple1 = ("a", "b" , "c")tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3)

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)