Python
Join Two Tuples To join two or more tuples you can use the + operator: Example Join two tuples: tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3)
('a', 'b', 'c', 1, 2, 3)
Python Tuples Tuple A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. Example Create a Tuple: thistuple = ("apple", "banana", "cherry") print(thistuple) Access Tuple Items You can access tuple items by referring to the index number, inside square brackets: Example Print the second item in the tuple: thistuple = ("apple", "banana", "cherry") print(thistuple[1])
('apple', 'banana', 'cherry') banana
Change Tuple Values Once 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. Example Convert 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)
('apple', 'kiwi', 'cherry')
Range of Indexes You 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. Example Return the third, fourth, and fifth item: thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[2:5]) #This will return the items from position 2 to 5. #Remember that the first item is position 0, #and note that the item in position 5 is NOT included thistuple: ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
('cherry', 'orange', 'kiwi')
Range of Negative Indexes Specify negative indexes if you want to start the search from the end of the tuple: Example This example returns the items from index -4 (included) to index -1 (excluded) thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[-4:-1]) #Negative indexing means starting from the end of the tuple. #This example returns the items from index -4 (included) to index -1 (excluded) #Remember that the last item has the index -1, thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[-4:-1])
('orange', 'kiwi', 'melon')
Python List count() Method Example Return the number of times the value "cherry" appears int the fruits list: fruits = ["apple", "banana", "cherry"] x = fruits.count("cherry")print(x)Definition and Usage The count() method returns the number of elements with the specified value. Syntax list.count(value) Parameter Values value Required. Any type (string, number, list, tuple, etc.). The value to search for. Return the number of times the value 9 appears int the list: fruits = [1, 4, 2, 9, 7, 8, 9, 3, 1] x = fruits.count(9) print(x)
2
Python List index() Method Example What is the position of the value "cherry": fruits = ['apple', 'banana', 'cherry'] x = fruits.index("cherry") print(x)
2
Tuple MethodsPython has two built-in methods that you can use on tuples. Method Description count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found Python Tuple count() Method thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5) x = thistuple.count(5) print(x)
2
Definition and Usage The index() method returns the position at the first occurrence of the specified value. Syntax list.index(elmnt) Parameter Values Parameter Description elmnt Required. Any type (string, number, list, etc.). The element to search for More Examples Example What is the position of the value 32: fruits = [4, 55, 64, 32, 16, 32] x = fruits.index(32) print(x)
3
List Length To determine how many items a list has, use the len() function: Example Print the number of items in the list: thislist = ["apple", "banana", "cherry"] print(len(thislist))
3
Python Tuple index() Method Example Search for the first occurrence of the value 8, and return its position: thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5) x = thistuple.index(8) print(x) Definition and Usage The index() method finds the first occurrence of the specified value. The index() method raises an exception if the value is not found. Syntaxtuple.index(value) Parameter Values Parameter Description value Required. The item to search for
3
Tuple Length To determine how many items a tuple has, use the len() method: Example Print the number of items in the tuple: thistuple = ("apple", "banana", "cherry") print(len(thistuple)) Add Items Once a tuple is created, you cannot add items to it. Tuples are unchangeable. thistuple = ("apple", "banana", "cherry") print(len(thistuple))
3
x = 5 print(type(x))
<class 'int'>
Create Tuple With One Item To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. Example One item tuple, remember the commma: thistuple = ("apple",) print(type(thistuple)) #NOT a tuple thistuple = ("apple") print(type(thistuple))
<class 'tuple'> <class 'str'>
Check if the phrase "ain" is NOT present in the following text: txt = "The rain in Spain stays mainly in the plain" x = "ain" not in txt print(x)
False
x = 5 print(not(x > 3 and x < 10))
False because not is used to reverse the result
x = ["apple", "banana"] y = ["apple", "banana"] z = x print(x is not z) print(x is not y) print(x != y)
False because z is the same object as x True because x is not the same object as y, even if they have the same content to demonstrate the difference between "is not" and "!=": this comparison returns False because x is equal to y
The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper())
HELLO, WORLD!
By looping through the lines of the file, you can read the whole file, line by line: Example Loop through the file line by line: f = open("demofile.txt", "r") for x in f: print(x)
Hello! Welcome to demofile.txt. This file is for testing purposes. Good Luck!
Example quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price))
I want to pay 49.95 dollars for 3 pieces of item 567.
The replace() method replaces a string with another string: a = "Hello, World!" print(a.replace("H", "J"))
Jello, World!
List Methods Python has a set of built-in methods that you can use on lists.
Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the item with the specified value reverse() Reverses the order of the list sort() Sorts the list
But we can combine strings and numbers by using the format() method! The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are: Example Use the format() method to insert numbers into strings: age = 36txt = "My name is John, and I am {}" print(txt.format(age))
My name is John, and I am 36
Open the file "demofile.txt" and overwrite the content: f = open("demofile.txt", "w") f.write("Woops! I have deleted the content!") f.close() #open and read the file after the appending: f = open("demofile.txt", "r") print(f.read())
Note: the "w" method will overwrite the entire file output Woops! I have deleted the content!
File Handling The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file: "r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists In addition you can specify if the file should be handled as binary or text mode "t" - Text - Default value. Text mode "b" - Binary - Binary mode (e.g. images) Syntax To open a file for reading it is enough to specify the name of the file: f = open("demofile.txt") The code above is the same as: f = open("demofile.txt", "rt") Because "r" for read, and "t" for text are the default values, you do not need to specify them. Note: Make sure the file exists, or else you will get an error.
Python File Open Open a File on the Server Assume we have the following file, located in the same folder as Python: demofile.txt Hello! Welcome to demofile.txtThis file is for testing purposes.Good Luck! To open the file, use the built-in open() function. The open() function returns a file object, which has a read() method for reading the content of the file: f = open("demofile.txt", "r") print(f.read())
Random Number
Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers: Example Import the random module, and display a random number between 1 and 9: import random print(random.randrange(1, 10))
String Methods
Python has a set of built-in methods that you can use on strings. Example The strip() method removes any whitespace from the beginning or the end: a = " Hello, World! " print(a.strip()) # returns "Hello, World!"
x = "awesome" def myfunc(): x = "fantastic" print("Python is " + x) myfunc() print("Python is " + x)
Python is fantastic Python is awesome
x = "awesome" def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x)
Python is fantastic change global
Create a New File To create a new file in Python, use the open() method, with one of the following parameters: "x" - Create - will create a file, returns an error if the file exist "a" - Append - will create a file if the specified file does not exist "w" - Write - will create a file if the specified file does not exist Create a file called "myfile.txt": f = open("myfile.txt", "x")
Result: a new empty file is created!
String Length
To get the length of a string, use the len() function. Example The len() function returns the length of a string: a = "Hello, World!" print(len(a))
Check String To check if a certain phrase or character is present in a string, we can use the keywords in or not in. Example Check if the phrase "ain" is present in the following text: txt = "The rain in Spain stays mainly in the plain" x = "ain" in txt print(x)
True
Python also has many built-in functions that returns a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type: Example Check if an object is an integer or not: x = 200 print(isinstance(x, int))
True
Most Values are True Almost any value is evaluated to True if it has some sort of content. Any string is True, except empty strings. Any number is True, except 0.Any list, tuple, set, and dictionary are True, except empty ones. Example The following will return True: bool("abc") bool(123) bool(["apple", "cherry", "banana"]) print(bool("abc")) print(bool(123)) print(bool(["apple", "cherry", "banana"]))
True True True
x = ["apple", "banana"] print("pineapple" not in x)
True because a sequence with the value "pineapple" is not in the list
txt = "We are the so-called \"Vikings\" from the north."
We are the so-called "Vikings" from the north
Python List sort() Method Example Sort the list alphabetically: cars = ['Ford', 'BMW', 'Volvo'] cars.sort() print(cars) Definition and Usage The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria(s).
['BMW', 'Ford', 'Volvo']
Sort the list by the length of the values and reversed: # A function that returns the length of the value: def myFunc(e): return len(e) cars = ['Ford', 'Mitsubishi', 'BMW', 'VW'] cars.sort(reverse=True, key=myFunc) print(cars)
['Mitsubish', 'Ford', 'BMW', 'VW']
Sort the list by the length of the values: # A function that returns the length of the value: def myFunc(e): return len(e) cars = ['Ford', 'Mitsubishi', 'BMW', 'VW'] cars.sort(key=myFunc) print(cars)
['VW', 'BMW', 'Ford', 'Mitsubishi']
Sort the list descending: cars = ['Ford', 'BMW', 'Volvo'] cars.sort(reverse=True) print(cars)
['Volvo', 'Ford', 'BMW']
Another way to join two lists are by appending all the items from list2 into list1, one by one: Example Append list2 into list1: list1 = ["a", "b" , "c"] list2 = [1, 2, 3] for x in list2: list1.append(x) print(list1)
['a', 'b', 'c', 1, 2, 3]
Join Two Lists There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator. Example Join two list: list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3)
['a', 'b', 'c', 1, 2, 3]
Or you can use the extend() method, which purpose is to add elements from one list to another list: Example Use the extend() method to add list2 at the end of list1: list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1)
['a', 'b', 'c', 1, 2, 3]
Python List extend() Method Example Add the elements of cars to the fruits list: fruits = ['apple', 'banana', 'cherry']cars = ['Ford', 'BMW', 'Volvo'] fruits.extend(cars) print(fruits) Syntax list.extend(iterable)
['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
Add Items To add an item to the end of the list, use the append() method: Example Using the append() method to append an item: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist)
['apple', 'banana', 'cherry', 'orange']
Python List append() Method Example Add an element to the fruits list: fruits = ['apple', 'banana', 'cherry'] fruits.append("orange") print(fruits) Definition and Usage The append() method appends an element to the end of the list. Syntaxlist.append(elmnt) Parameter Values elmnt Required. An element of any type (string, number, object etc.)
['apple', 'banana', 'cherry', 'orange']
Definition and Usage The extend() method adds the specified list elements (or any iterable) to the end of the current list. Parameter Description iterable Required. Any iterable (list, set, tuple, etc.) More Examples Example Add a tuple to the fruits list: fruits = ['apple', 'banana', 'cherry'] points = (1, 4, 5, 9) fruits.extend(points) print(fruits)
['apple', 'banana', 'cherry', 1, 4, 5, 9]
a = ["apple", "banana", "cherry"] b = ["Ford", "BMW","Volvo"] a.append(b) print(a)
['apple', 'banana', 'cherry', ['Ford', 'BMW', 'Volvo']]
Another way to make a copy is to use the built-in method list(). Example Make a copy of a list with the list() method: thislist = ["apple", "banana", "cherry"] mylist = list(thislist) print(mylist)
['apple', 'banana', 'cherry']
Copy a List You 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(). Example Make a copy of a list with the copy() method: thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist)
['apple', 'banana', 'cherry']
The list() Constructor It is also possible to use the list() constructor to make a new list. Example Using the list() constructor to make a List: thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist)
['apple', 'banana', 'cherry']
Example The pop() method removes the specified index, (or the last item if index is not specified): thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) Example The del keyword removes the specified index: thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist)
['apple', 'banana'] ['banana', 'cherry']
Python List remove() Method Example Remove the "banana" element of the fruit list: fruits = ['apple', 'banana', 'cherry'] fruits.remove("banana")print(fruits) Definition and Usage The remove() method removes the first occurrence of the element with the specified value. Syntax list.remove(elmnt) Parameter Values Parameter Description elmnt Required. Any type (string, number, list etc.) The element you want to remove
['apple', 'cherry']
Remove Item There are several methods to remove items from a list: Example The remove() method removes the specified item: thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist)
['apple', 'cherry']
Python List pop() Method Example Remove the second element of the fruit list: fruits = ['apple', 'banana', 'cherry'] fruits.pop(1) print(fruits) Definition and Usage The pop() method removes the element at the specified position. Syntax list.pop(pos) pos Optional. A number specifying the position of the element you want to remove, default value is -1, which returns the last item Example Return the removed element: fruits = ['apple', 'banana', 'cherry'] x = fruits.pop(1) print(x)
['apple', 'cherry'] banana
Python List insert() Method Example Insert the value "orange" as the second element of the fruit list: fruits = ['apple', 'banana', 'cherry'] fruits.insert(1, "orange") print(fruits) Definition and Usage The insert() method inserts the specified value at the specified position. Syntax list.insert(pos, elmnt) Parameter Description pos Required. A number specifying in which position to insert the value elmnt Required. An element of any type (string, number, object etc.)
['apple', 'orange', 'banana', 'cherry']
To add an item at the specified index, use the insert() method: Example Insert an item as the second position: thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist)
['apple', 'orange', 'banana', 'cherry']
Example This example returns the items from "cherry" and to the end: By leaving out the end value, the range will go on to the end of the list: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:]) #This will return the items from index 2 to the end. #Remember that index 0 is the first item, and index 2 is the third
['cheery', 'orange', 'kiwi', 'melon', 'mango']
Reverse the order of the fruit list: fruits = ['apple', 'banana', 'cherry'] fruits.reverse() print(fruits)
['cherry', 'banana', 'apple']
Range of Negative Indexes Specify negative indexes if you want to start the search from the end of the list: Example This example returns the items from index -4 (included) to index -1 (excluded) thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[-4:-1]) #Negative indexing means starting from the end of the list. #This example returns the items from index -4 (included) to index -1 (excluded) #Remember that the last item has the index -1,
['orange', 'kiwi', 'melon']
Remove all elements from the fruits list: fruits = ["apple", "banana", "cherry"] fruits.clear() print(fruits)
[]
The clear() method empties the list: thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist)
[]
The clear() method removes all the elements from a list. Syntax list.clear() Parameter Values No parameters Python List copy() Method fruits = ["apple", "banana", "cherry"] x = fruits.copy() print(x)
[] ['apple', 'banana', 'cherry']
Sort a list of dictionaries based on the "year" value of the dictionaries: def myFunc(e): return e['year'] cars = [ {'car': 'Ford', 'year': 2005}, {'car': 'Mitsubishi', 'year': 2000}, {'car': 'BMW', 'year': 2019}, {'car': 'VW', 'year': 2011}] cars.sort(key=myFunc) print(cars)
[{'car': 'Mitsubish', 'year': 2000}, (continua)]}
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!']
Loop Through a List You can loop through the list items by using a for loop: Example Print all items in the list, one by one: thislist = ["apple", "banana", "cherry"] for x in thislist: print(x)
apple banana cherry
Loop Through a Tuple You can loop through the tuple items by using a for loop. Example Iterate through the items and print the values: thistuple = ("apple", "banana", "cherry") for x in thistuple: print(x) Check if Item Exists To determine if a specified item is present in a tuple use the in keyword: Example Check if "apple" is present in the tuple: thistuple = ("apple", "banana", "cherry") if "apple" in thistuple: print("Yes, 'apple' is in the fruits tuple")
apple banana cherry Yes, 'apple' is in the fruits tupple
Close Files It is a good practice to always close the file when you are done with it. Example Close the file when you are finish with it: f = open("demofile.txt", "r") print(f.readline()) f.close() Note: You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.
close file
Example The del keyword can also delete the list completely: thislist = ["apple", "banana", "cherry"] del thislist print(thislist) #this will cause an error because you have successfully deleted "thislist".
error - you deleted the list
Remove Items Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely: Example The del keyword can delete the tuple completely: thistuple = ("apple", "banana", "cherry")del thistuple print(thistuple) #this will raise an error because the tuple no longer exists
error, tuple no longer exists
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Python Identity Operators Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
is is not
f the file is located in a different location, you will have to specify the file path, like this: Example Open a file on a different location: f = open("C:/Users/aviji/Documents/ISM4930/iris.csv", "r")print(f.read())
open file
Read Only Parts of the File By default the read() method returns the whole text, but you can also specify how many characters you want to return: f = open("demofile.txt", "r") print(f.read(5))Read Lines You can return one line by using the readline() method: f = open("C:/Users/aviji/Documents/ISM4930/iris.csv", "r")print(f.readline())
read parts of the file
By calling readline() two times, you can read the two first lines: Example Read two lines of the file: f = open("C:/Users/aviji/Documents/ISM4930/iris.csv", "r") print(f.readline()) print(f.readline())
reads first two lines
Python Membership Operators Membership operators are used to test if a sequence is presented in an object: in not in x = ["apple", "banana"] print("banana" in x)
returns True because a sequence with the value "banana" is in the list
x = ["apple", "banana"] y = ["apple", "banana"] z = x print(x is z) print(x is y) print(x == y)
true because z is the same object as x False because x is not the same object as y, even if they have the same content to demonstrate the difference between "is" and "==": this comparison returns True because x is equal to y
Definition and Usage The count() method returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter Values
value Required. The item to search for
Python File Write Write to an Existing File To write to an existing file, you must add a parameter to the open() function: "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content Example Open the file "demofile.txt" and append content to the file: f = open("demofile.txt", "a") f.write("Now the file has more content!") f.close() #open and read the file after the appending: f = open("demofile.txt", "r") print(f.read())
write to an existing file
Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3 y = 12E4 z = -87.7e100
If you want to specify the data type, you can use the following constructor functions:
x = str("Hello World") str x = int(20) int x = float(20.5) float x = complex(1j) complex x = list(("apple", "banana", "cherry")) list x = tuple(("apple", "banana", "cherry")) tuple x = range(6) range x = dict(name="John", age=36)dict x = set(("apple", "banana", "cherry")) set x = frozenset(("apple", "banana", "cherry")) frozenset x = bool(5) bool x = bytes(5) bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview
Python Lists Python Collections (Arrays) There are four collection data types in the Python programming language:
•List is a collection which is ordered and changeable. Allows duplicate members. •Tuple is a collection which is ordered and unchangeable. Allows duplicate members. •Set is a collection which is unordered and unindexed. No duplicate members. •Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.