Python

Data Types and Operators

Welcome to this lesson on Data Types and Operators! You'll learn about:

  • Data Types: Integers, Floats, Booleans,

Strings, Lists, Tuples, Sets, Dictionaries

  • Operators: Arithmetic, Assignment, Comparison, Logical, Membership, Identity

  • Built-In Functions, Compound Data Structures, Type Conversion

  • Whitespace and Style Guidelines

1. Print() function in python:

You will be seeing this print function very frequently in python programming. It helps us to see what exactly is happening in our code.

Try to run the next lines of code and see what happens next:

In [ ]:

2+7 2*7

  • You will see that even though you had written 2 lines of code only the last line of code gets seen in the output area.

Now this happens because you haven't told python what to alctually do with it.

This is where print() comes in. print() in python is a useful builtin function that we can use to display input value as text in the output.

In [ ]:

print(2+7) print(2*7)

In [ ]:

print('Hello World!!!!')

2. Arithmetic Operators

An arithmetic operator is a mathematical function that takes 2 operands and performs a calculation on them. Lets take the previous example, we multiplied 2 and 7 here 2 and 7 are the operands and this asterisks is the arithmetic operator for multiplication. Python has several arithmetic operators most of which follow the usual rules of mathematics. Lets look at them now.

  • + Addition

  • - Subtraction

  • * Multiplication

  • / Division

  • % Mod (the remainder after dividing)

  • ** Exponentiation (note that ^ does not do this operation, as you might have seen in other languages)

  • // Divides and rounds down to the nearest integer

[ Now sometime people might confuse this (^)Caret symbol for Exponentiation as you might have seen it in other languages but in python this symbol is used to do bitwise XOR operation. As learning bitwise operation is not necessary for this course we will not be covering it but you can surely check out the link in the resources below to learn more. ]

Task:

Now perform all the arithematic operations on the numbers 7 and 2.

In [ ]:

# While showing the output use print() # add 7 and 2 below # substract 2 from 7 below # multiply 7 and 2 below # divide 7 by 2 below # remainder after we divide 7 by 2 below # 7 raise to the power 2 below # divide 7 by 2 nd round it to the nearest integer

Expected output:

9
5
14
3.5
1
49
3

3. Order of Operations:

Now Arithmetic operators in python follow the BEDMAS order of operations.
Look at this mathematical equation (2+3*5) what do you think will be the answer 25 or 17. The answer is 17 because in maths we follow a convention called as the order of operations BEDMAS ie.

  • Brackets

  • Exponents

  • Division and Multiplication (left to right)

  • Addition and Substraction (left to right)

Preference given to the operator that comes first in BEDMAS.

Question:

In this quiz you're going to do some calculations for your bills. Your net expenditure for the past 5 months has been 1200, 2000, 800, 1500 and 1700. What is your average monthly expenditure.

In [ ]:

# write your code here

Expected output:

1440.0

Question:

In this quiz you're going to do some calculations for a mason. Two rooms in a house needs to be filled. One room is 4 ft wide by 11 ft long, the other is 5 ft wide by 9 ft long. Tiles come in packages of 7 and each tile is 1ftx1ft in size

  1. How many tiles are needed?

  2. You buy 17 packages each containing 6 tiles each. How many tiles will be left over?

In [ ]:

# write the code that calculates how many tiles are needed down below. # write the code that calculates how many tiles will be left over.

Expected output:

89
13

4. Variables:

Understanding variables is very important in any programming language they are used all the time in python. Using variables in place of direct numbers have many advantages. Variables are used to store information to be referenced and manipulated in a computer program.

Creating a new variable in python is very simple, lets create one together, here in this example below the variable name is month, the equal sign is the assignment operator and the value of the variable is 12.

In [ ]:

month=12 print(month)

Now its your turn create a variable named rent with its value being 1700

In [ ]:

# create and print the varibale rent down below

Expected output:

1700

In any case, whatever term is on the left side, is now a name for whatever value is on the right side. Once a value has been assigned to a variable name, you can access the value from the variable name.

For example if we run this code we will get 3 as the output here as in the first line we assigned 3 to a and in the second line we assigned a to b so when we print b we get 3 as the output.

In [ ]:

a=3 b=a print(b)

If we don't declare the variable and try to print the output then we will get the following error

In [ ]:

print(x)

5. Multiple Assignment Operator:

Suppose you are making a program where in you enter the dimensions of the tank and it will give the volume of the tank as the output. So you can write code as:

In [ ]:

height = 3 length = 6 width = 2 volume = height length width print(volume)

Now python has a very useful way to assign multiple variables together in a single line using multiple assignment like this:

In [ ]:

# this will now assign 3 to height, 6 to length and 2 to width just as before. height , length , width = 3 , 6 , 2 volume = height length width print(volume)

ou can use this when you are assigning closely related variables such as height width length or coordinates such as x, y , z of an object.

Question:

Find the length of the vector with its start coordinates as the origin and the end coordinates as (4,5,6).

length = squareroot(x^2 + y^2 + z^2)

In [ ]:

# write your code here

Expected output:

8.774964387392123

6. Variable Naming Conventions:

There are some rules we need to follow while giving a name for a Python variable.

  • Rule-1: You should start variable name with an alphabet or underscore(_) character.

  • Rule-2: A variable name can only contain A-Z,a-z,0-9 and underscore(_).

  • Rule-3: You cannot start the variable name with a number.

  • Rule-4: You cannot use special characters with the variable name such as such as $,%,#,&,@.-,^ etc.

  • Rule-5: Variable names are case sensitive. For example str and Str are two different variables.

  • Rule-6: Do not use reserve keyword as a variable name for example keywords like class, for, def, del, is, else, try, from, etc. more examples are given below and as we go through the course we will come across many more. Creating names that are descriptive of the values often will help you avoid using any of these words.

In [ ]:

#Allowed variable names x=2 y="Hello" mypython="PythonGuides" my_python="PythonGuides" mypython="PythonGuides" _mypython="PythonGuides" MYPYTHON="PythonGuides" myPython="PythonGuides" myPython7="PythonGuides"

In [ ]:

#Variable name not Allowed 7mypython="PythonGuides" -mypython="PythonGuides" myPy@thon="PythonGuides" my Python="PythonGuides" for="PythonGuides" #It shows invalid syntax. #It will execute one by one and will show the error.

Also there are some naming convention that needs to be followed like:

  • try to keep the name of the variables descriptive short but descriptive. for example: when taking inputs for the height of a tree of a box the appropriate variable name will be just height not x not h not height_of_the_tree.

  • Also the pythonic way to name variables is to use all lowercase letters and underscores to separate words.

In [ ]:

# pythonic way my_height = 58 my_lat = 40 my_long = 105

In [ ]:

# not pythonic way my height = 58 # wont work MYLONG = 40 # will work still avoid using it MyLat = 105 # will work still avoid using it

Though the last two of these would work in python, they are not pythonic ways to name variables. The way we name variables is called snake case, because we tend to connect the words with underscores.

What if we want to change or update the value of a variable for example take the example of rent = 1700, suppose the rent has hiked and the new rent is 2000 we can just assign the variable its new value as:

In [ ]:

rent = 1700 rent = 2000 print(rent)

This is called overwriting the variable , i.e, When a new value is assigned to a variable, the old one is forgotten.

If we had then caused some damages to the property during our crazy house party and we have to pay for them then we can just apply these changes directly to this variable.

In [ ]:

rent = 1700 rent = 2000 rent =rent + 700 print(rent)

in the line 3 the variable rent is being assigned to itself plus 700 which results to 2700.

Because such increment and assignment operations are very common python has a very special assignment operator for this.

In [ ]:

rent = 1700 rent = 2000 rent += 700 print(rent)

we can actually use this += operator to tell python that we are incrementing the value on the left by the value on the right. += is a example of assignment operator -= *= /= are some more examples of assignment operators. All of these operators just apply arithmetic operation to the variable on the left with the value on the right which makes your code more concise and easier to read and understand.

Question:

You are managing your finances using python:

  • complete the tasks mentioned in the comments. and then print the amount left in your bank.

Note that this code uses scientific notation to define large numbers. 1.2e6 is equal to 1.2 10 ** 6 which is equal to 1200000.*

In [ ]:

# the amount of money in your bank account is 1.2e5 amt = 1.2e6 # money recieved every year in form of salary salary = 9.3e5 # decrease the salary by 30% as tax paied to the government. # Add the salary to the bank account amt variable # increase the amt by 4% that you recieved from the bank as intrest # substract 1.2e5 from amt as the rent paied # print the new value of the amt variable

Expected output:

1805040.0

7. Integers and Floats:

So far the numbers that we have dealt with were mostly whole numbers or integers, but as you may have notices that other types of numbers also do exist. For example dividing one integer by another gives us a number that isn't an integer, in python we represent such a number as a float, which is short for floating point number.

In [ ]:

print(3/2)

Numbers with a decimal point, such as 3.14, are called floating-point numbers (or floats). Note that even though the value 42 is an integer, the value 42.0 would be a floating-point number. And if 2 integers are divided then also we get float as an answer.

You can check the datatype of any value by using the builtin function of type, that returns the type of an object. Here as you can see they type of a number without a decimal and the type of a number with a decimal.

In [ ]:

a = 3 b = 2.5 print(type(a)) print(type(b))

An operation involving an int and a float will always give float as its output. We can also covert one datatype to another by constructing new objects of those types with int and float.

When we convert a float to an int the part after the decimal point is dropped and hence there is no rounding. eg 28.9 will be cut to 28.

Similarly converting int to float just adds a decimal at the end of the number and a 0 after that. example 3 will become 3.0

In [ ]:

a = float(3) b = int(28.9) print(a) print(b)

Another point that you need to keep in mind is float are an approximation to the number they represent. As float can represent very large range of numbers python must use approximation to represent these numbers. For example this floating point number 0.23 is in reality slightly more than 0.23. such that if we add up 0.23 to itself a few times and check its equality to the expected resultant it will be different. Although the difference is very small but it exists never the less and you should know about it.

In [ ]:

print(0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23+ 0.23 + 0.23 == 6.9)

8. Division by Zero and Errors:

What happens if you divide by zero in Python? Try it out! Test run this code and see what happens.

In [ ]:

print(4/0)

what you should have seen when you submitted the Divide by Zero code above, Traceback means

"What was the programming doing when it broke"!

This part is usually less helpful than the very last line of your error. Though you can dig through the rest of the error, looking at just the final line ZeroDivisionError, and the message says we divided by zero. Python is enforcing the rules of arithmetic!

In general, there are two types of errors to look out for

  • Exceptions

  • Syntax

An Exception is a problem that occurs when the code is running, but a 'Syntax Error' is a problem detected when Python checks the code before it runs it. For more information, see the Python tutorial page on Errors and Exceptions.

9. Boolean Datatype, Comparison and Logical Operators:

Bool is another datatype that is commonly used in Python. Bool is short for Boolean which can have a value of either True or False. Boolean algebra is the branch of algebra in which the values of the variables are the truth values true or false. Boolean algebra us the framework on which all electronic devices and built and exists fundamentally in every line of code inside a computer. In python we can easily assign boolean values like this:

In [ ]:

python_awsome = True doumentation_bad = False

We can use comparison operators to compare 2 values and produce boolean results like:

In [ ]:

a = 3 > 1 print(a)

Here 3 is greater than 1 so printing out the output gives us a boolean value to true. There are many comparison operators in python, as you can see here are all of them.

As you will see the function of all these comparison operators are evident from their names itself these are less than, greater than , less than or equal to, greater than or equal to, not equal to.

Working with boolean has its own set of operators called as logical operators. These operators very useful when working with boolean, and evaluates if both the sides are true, OR evaluates if atleast one side is true and not evaluates the inverse of the input boolean.

Lets understand if via an example:

In [ ]:

rent = 1200 is_affordable = rent > 1000 and rent < 2000 print(is_affordable)

Here we check if the rent of a house is affordable or not, here in the second line we evaluate both the sides ie rent > 1000, yes, so it is true while the second condition is rent < 200, that too is true. as both the condition on the left and right side of and is true hence the boolean value of true will be assigned to the is_affordable variable. In other words if the rent is greater than 1000 and less than 2000 then only it is affordable.

And here you can see how not works:

In [ ]:

rent = 1200 is_affordable = not(rent > 1000 and rent < 2000) #"not" just inverts bool value print(is_affordable)

Question:

Is Mumbai more dense than Delhi?

Print True* if it is and False if it is not.*

In [ ]:

mum_population, mum_area = 20411000, 4355 del_population, del_area = 30291000, 1484 mum_francisco_pop_density = mum_population/mum_area del_de_janeiro_pop_density = del_population/del_area # Print True if Mumbai is denser than Delhi, and False otherwise

Expected output:

False

10. Strings:

Python has another datatype in its toolkit called as Strings, as the name suggest this datatype deals with characters words and text. String is a immutable order of sequences of characters (eg, Letters, numbers, spaces and symbols. We will be explaining what does immutable order means later on.

You can create a string by using quotes as seen here, you can use either single / double quotes they both work equally well but there are some cases where you might prefer one over the other which we will be discussing below.

In [ ]:

# using Double Quotes print("ShapeAI") # using Single Quotes print('ShapeAI')

In this example we printed the word ShapeAI using single and double quotes and got the same output ShapeAI.

We can also assign a string to a variable just like float and int.

In [ ]:

motto = "Learn | Code | Compete | Intern" print(motto)

Strings in Python are shown as the variable type str.

In [ ]:

type(motto)

*String can contain any character number symbol space within the quotes.

However if we want to have quotes inside the string we get an error.*

In [ ]:

dialogue = "shiva said, "you learn as you grow""

Python provides 2 easy ways to handle such problem:

  1. Place the string in single quotes rather than double quotes. This will solve your problem for having double quotes within the string. But sometimes you will want to have both double and single quotes in your string in that case this will prove to be a problem.

In [ ]:

dialogue = 'shiva said, "you learn as you grow"' print(dialogue)

  1. In that case we can use a backslash to skip quotes as you can see in this example. The backslash helps python to know that the the single quote should be interpreted as part of the string rather than the quote that ends the string.

In [ ]:

dialogue = '"shiva you\'re bag is red"' print(dialogue)

There are a few operators that we use on floats and ints that can also be used on strings. For example we can use the '+' to combine / concatenate 2 strings together and we can use '*' to repeat the string let us look at an example for each.

In [ ]:

print("hello" + "world") print("hello" + " " + "world")

here in this example we can see that using the plus arithmetic operator we get helloworld* written together but this word that is printed out has no meaning, we need to have a space between both the words to have a meaning. We can add another string containing just a space in between the words to do so.*

In [ ]:

word = "hello" print(word * 5)

Now in the second example we can see that using the multiplication operator on a string we get repetition of the same word as many time as the number we multiplied the string by in the output.

However unlike multiplication and addition operators the other arithmetic operators like division and subtraction cannot be used on strings any attempt to do so would result in an error that string is an unsupported datatype for the division/subtraction operator.

In [ ]:

word_1 = "hello" word_2 = "world" print(word_1 / word_2)

A useful builtin function for string datatypes is len() which stands for length. As the name suggests (it returns the length of an object ie., it returns the no of characters in a string.

It takes in values in a parenthesis and returns the length of the string. len() is a little different from print() as the value returned from length can be stored in a variable as seen in the example here. The len() function outputs a value 7 that is then stored in a variable called as word_length which is then printed out.

In [ ]:

word_length = len("ShapeAI") print(word_length)

Question:

The line of code in the following code block will cause a SyntaxError, thanks to the misuse of quotation marks. First run it with Test Run to view the error message. Then resolve the problem so that the quote (from Mahatama Gandhi) is correctly assigned to the variable gandhi_quote.

In [ ]:

# TODO: Fix this string! gandhi_quote = 'If you don't ask, you don't get it'

Question:

In this question you have to print the accuracy logs of a model in training.

In [ ]:

model = "VGG16" iteration = "150" accuracy = "67.98" # TODO: print a log message using the variables above # This message should have the same format as this one: # "the accuracy of ResNET50 model in 100th iteration is: 42.16%"

Question:

Use string concatination and len() function to fing the length of a persons complete name and store it in the variable name_length.

As a business card designer find if the name can fit into a business card.

In [ ]:

given_name = "Rahul" middle_names = "Shastri" family_name = "Mishra" name_length = #todo: calculate how long this name is # Now we check to make sure that the name fits within the driving license character limit # Nothing you need to do here driving_license_character_limit = 28 print(name_length <= driving_license_character_limit)

11. Type and Type Conversion Revision:

Till now we have covered 4 different datatypes int, float, bool and string. As you can recall from the previous classes python has a builtin function called as type that returns the type of an object.

In [ ]:

print(type(75)) print(type(75.0)) print(type("75")) print(type(True))

Look at the code example we can see that even though the first 3 values appear to be same they can be encoded into different datatypes each with their own set of functions operations and uses.

This is to note that here we have called the function print on another function type to output the return value of the function type. In such a case always the function inside the parenthesis is run first ie. here it will be type.

Different types have different properties with their own set of functions operations and uses and hence while choosing a variable you need to choose the correct set of datatype for it depending upon how you care going to use it this is very important.

There might be sometimes when you don't have the control over the type of the data being provided to you like one that has been received from a user as in input. But the good news is that python allows you to create new objects from old and change the datatypes for these new objects. As we had previously seen in the integers and floats video.

For example here we created a float ie 3.0 from an int 3 and assigned it to a new variable called decimal

In [ ]:

decimal = float(3) print(decimal) print(type(decimal))

In this next example we created a string from the integer variable marks and used that to create a larger string.

In [ ]:

marks = 15 subject = "coding" semester = "first" result = "I scored " + str(marks) + " in " + subject + " during my " + semester + " semester." print(result)

we can also create an float from string

In [ ]:

marks = "15" print(type(marks)) marks = float(marks) print(type(marks))

Question:

In this quiz, you’ll need to change the types of the input and output data in order to get the result you want.

Calculate and print the total sales for the week from the data provided. Print out a string of the form "This week's total sales: xxx", where xxx will be the actual total of all the numbers. You’ll need to change the type of the input data in order to calculate that total.

In [ ]:

mon_sales = "121" tues_sales = "105" wed_sales = "110" thurs_sales = "98" fri_sales = "95" #TODO: Print a string with this format: This week's total sales: xxx # You will probably need to write some lines of code before the print statement. total_sales = (float(mon_sales) + float(tues_sales) + float(wed_sales) + float(thurs_sales) + float(fri_sales)) print("This week\'s total sales: " + str(total_sales))

12. String Methods:

Methods are like some of the functions you have already seen:

  • len("this")

  • type(12)

  • print("Hello world")

These three above are functions - notice they use parentheses, and accept one or more arguments. Functions will be studied in much more detail in a later lesson!

A method in Python behaves similarly to a function. Methods actually are functions that are called using dot notation. For example, lower() is a string method that can be used like this, on a string called "sample string": sample_string.lower().

Methods are specific to the data type for a particular variable. So there are some built-in methods that are available for all strings, different methods that are available for all integers, etc.

Below is an image that shows some methods that are possible with any string.

screen-shot-2018-02-01-at-12.10.40-am.png

Each of these methods accepts the string itself as the first argument of the method. However, they also could receive additional arguments, that are passed inside the parentheses. Let's look at the output for a few examples.

In [ ]:

my_string = "ShapeAI" print(my_string.islower()) print(my_string.count('a')) print(my_string.find('a'))

You can see that the count and find methods both take another argument. However, the .islower() method does not accept another argument.

No professional has all the methods memorized, which is why understanding how to use documentation and find answers is so important. Gaining a strong grasp of the foundations of programming will allow you to use those foundations to use documentation to build so much more than someone who tries to memorize all the built-in methods in Python.

12.a. One important string method: format()

We will be using the format() string method a good bit in our future work in Python, and you will find it very valuable in your coding, especially with your print statements.

We can best illustrate how to use format() by looking at some examples:

In [ ]:

# Example 1 print("EG:1") print("Mohammed has {} balloons".format(27)) # Example 2 print("EG:2") animal = "dog" action = "bite" print("Does your {} {}?".format(animal, action)) # Example 3 print("EG:3") maria_string = "Maria loves {} and {}" print(maria_string.format("math","statistics"))

Notice how in each example, the number of pairs of curly braces {} you use inside the string is the same as the number of replacements you want to make using the values inside format().

More advanced students can learn more about the formal syntax for using the format() string method here.

13. Lists and Membership Operators:

Data structures are containers that organize and group data types together in different ways. A list is one of the most common and basic data structures in Python. It is a mutable ordered sequence of elements.

The code below defines a variable students which contains a list of strings. Each element in the list is a string that signifies the name of a student.

The data inside a list can be a mixture of any number and combination of diffrent data types.

In [ ]:

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner']

List are ordered, we can look up individual elements by their index, we can look elements from a list just like we have done below.

In [ ]:

print(students[0]) print(students[1]) print(students[2])

Notice that the first element in the list is accessed by the index 0, many programming language follow this convection called as zero based indexing.

We can also access the elements from the end of the list using negative index as seen in the examples below.

In [ ]:

print(students[-1]) print(students[-2]) print(students[-3])

If you try to access an index in a list that doesn't exist then you will get an Error as seen below.

In [ ]:

print(students[20])

Question:

Try to use len() to pull the last element from the above list

In [ ]:

# TODO: write your code here students[len(students)-1]

13.a. Membership Operators:[Lists]

In addition to accessing individual elements froma a list, we can use pythons sliceing notation to access a subsequence of a list.

Slicing means using indicies to slice off parts of an object like list/string. Look at an example

In [ ]:

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce', 'henry', 'clark', 'diana'] student = "Barry" # slice a particular range marvel = students[4:7] flash = student[1:3] print(marvel) print(flash)

In [ ]:

# slice from the end dc = students[7:] flash = student[1:] print(dc) print(flash)

In [ ]:

# slice from the begining normal = students[:4] flash = student[:3] print(normal) print(flash)

In [ ]:

# length of the list and the string print(len(students)) print(len(student))

Of the types we have seen lists are most familier to strings, both supports the len() function, indexing and slicing.

Here above you have seen that the length of a string is the no of characters in the string, while the length of a list is the no of elements in the list.

Another thing that they both supports aare membership operators:

  • in: evaluates if an object on the left side is included in the object on the right side.

  • not in: evaluates if object on left side is not included in object on right side.

In [ ]:

greeting = "Hello there" print('her' in greeting, 'her' not in greeting)

In [ ]:

print('ShapeAI' in students, 'ShapeAI' not in students)

13.b. Mutability and Order:

So how are Lists diffrent from Strings, both supporst slicing, indexing, in and not in operators.

The most obvious diffrence between them is that string is a sequence of characters while list's elements can be any type of bojects string, integers, floats orr bools.

A more important diference is that lists can be modified but string can't. Look at the example below to understand more.

In [ ]:

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce', 'henry', 'clark', 'diana'] students[2] = 'ben' print(students)

In [ ]:

student = "Barry" student[1] = "e" print(student)

Mutability is about whether or not we can change an object once it has been created. If an object (like a list or string) can be changed (like a list can), then it is called mutable. However, if an object cannot be changed without creating a completely new object (like strings), then the object is considered immutable.

Order is about whether the position of an element in the object can be used to access the element. Both strings and lists are ordered. We can use the order to access parts of a list and string.

However, you will see some data types in the next sections that will be unordered. For each of the upcoming data structures you see, it is useful to understand how you index, are they mutable, and are they ordered. Knowing this about the data structure is really useful!

Additionally, you will see how these each have different methods, so why you would use one data structure vs. another is largely dependent on these properties, and what you can easily do with it!

Previously when we created a variable that heald an immutable object like string, the value of the immutable object was saved in memory. Like as you can see below

In [ ]:

student = "pam" character = student print(character) character = "peter" print(character) print(student)

Lists are diffrent from strings as they are mutable as can be seen from the example below

In [ ]:

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce', 'henry', 'clark', 'diana'] characters = students print(characters) characters[1]= "peter" print(characters) print(students)

There are some useful functions for lists that you should get familier with.

  1. len(): returns how many elements does the list has.

  2. max(): returns the greatest element of a list.

  3. min(): returns the smallest element of a list.

  4. sorted(): returns a copy of the list, in order from smallest to the largest. leaving the orignal list unchanged

max element in a list of integers is the largest integer, while in the case of string is the string that will come last if the list was sorted alphabetically.

In [ ]:

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce', 'henry', 'clark', 'diana'] student = "barry" print(max(students)) print(max(student))

a point to note is that even though you can have a list cntaining int and string a max function will be undefined upon such a list.

In [ ]:

max([2, 'two'])

In [ ]:

characters = sorted(students) print(characters)

Join() is an other useful function for lists(string lists), Join is a string method that takes a list of strings as an argument, and returns a string consisting of the list elements joined by a separator string. Look at the example below to understand.

In [ ]:

sep_str = "\n".join(["Jack", "O", "Lantern"]) print(sep_str)

In this example we use the string "\n" as the separator so that there is a newline between each element. We can also use other strings as separators with .join. Here we use a hyphen.

In [ ]:

name = "-".join(["Jack", "O", "Lantern"]) print(name)

It is important to remember to separate each of the items in the list you are joining with a comma (,). Forgetting to do so will not trigger an error, but will also give you unexpected results.

append() is an other useful method that adds an element to the end of a list.

In [ ]:

letters = ['a', 'b', 'c', 'd'] letters.append('e') print(letters)

14. Tuples:

A tuple is another useful container. It's a data type for immutable ordered sequences of elements. They are often used to store related pieces of information. Consider this example involving (x, y, z) coordinates:

In [ ]:

vector = (4, 5, 9) print("x-coordinate:", vector[0]) print("y-coordinate:", vector[1]) print("z-coordinate:", vector[2])

Tuples are similar to lists in that they store an ordered collection of objects which can be accessed by their indices. Unlike lists, however, tuples are immutable - you can't add and remove items from tuples, or sort them in place.

Tuples can also be used to assign multiple variables in a compact way.

The parentheses are optional when defining tuples, and programmers frequently omit them if parentheses don't clarify the code.

In [ ]:

location = 108.7774, 92.5556 latitude, longtitude = location print("The coordinates are {} x {}".format(latitude, longtitude))

In the second line, two variables are assigned from the content of the tuple location. This is called tuple unpacking. You can use tuple unpacking to assign the information from a tuple into multiple variables without having to access them one by one and make multiple assignment statements.

If we won't need to use location directly, we could shorten those two lines of code into a single line that assigns three variables in one go!

In [ ]:

location = 108.7774, 92.5556 print("The coordinates are {} x {}".format(latitude, longtitude))

15. Sets:

A set is a data type for mutable unordered collections of unique elements. One application of a set is to quickly remove duplicates from a list.

In [ ]:

numbers = [1, 2, 6, 3, 1, 1, 6] unique_nums = set(numbers) print(unique_nums)

Sets support the in operator the same as lists do. You can add elements to sets using the add method, and remove elements using the pop method, similar to lists. Although, when you pop an element from a set, a random element is removed. Remember that sets, unlike lists, are unordered so there is no "last element".

In [ ]:

fruit = {"apple", "banana", "orange", "grapefruit"} # define a set print("watermelon" in fruit) # check for element fruit.add("watermelon") # add an element print(fruit) print(fruit.pop()) # remove a random element print(fruit)

16. Dictionaries and Identity Operators:

A dictionary is a mutable data type that stores mappings of unique keys to values. Here's a dictionary that stores elements and their atomic numbers.

In [ ]:

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}

Dictionaries can have keys of any immutable type, like integers or tuples, not just strings. It's not even necessary for every key to have the same type! We can look up values or insert new values in the dictionary using square brackets that enclose the key.

In [ ]:

print(elements["helium"]) # print the value mapped to "helium" elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary

We can check whether a value is in a dictionary the same way we check whether a value is in a list or set with the in keyword. Dicts have a related method that's also useful, get(). get() looks up values in a dictionary, but unlike square brackets, get returns None (or a default value of your choice) if the key isn't found.

In [ ]:

print("carbon" in elements) print(elements.get("dilithium"))

Carbon is in the dictionary, so True is printed. Dilithium isn’t in our dictionary so None is returned by get and then printed. If you expect lookups to sometimes fail, get might be a better tool than normal square bracket lookups because errors can crash your program.

16.a. Keyword Operators:

  • is: evaluates if both sides have the same identity

  • is not evaluates if both sides have different identities

You can check if a key returned None with the is operator. You can check for the opposite using is not.

In [ ]:

n = elements.get("dilithium") print(n is None) print(n is not None)

Task:

Define a dictionary named population that contains this data:

Keys -> Values

New York -> 17.8

Spain -> 13.3

Dhaka -> 13.0

Mumbai -> 12.5

In [ ]:

population = {"New York":17.8, "Spain":13.3, "Dhaka":13.0, "Mumbai":12.5} print(population)

16.b. Get() with a Default Value:

Dictionaries have a related method that's also useful, get(). get() looks up values in a dictionary, but unlike looking up values with square brackets, get() returns None (or a default value of your choice) if the key isn't found. If you expect lookups to sometimes fail, get() might be a better tool than normal square bracket lookups.

In [ ]:

print(population.get('London'))

In [ ]:

population['London']

In [ ]:

population.get('London', 'There\'s no such place!')

In the last example we specified a default value (the string 'There's no such element!') to be returned instead of None when the key is not found.

16.c. Compound Data Structures:

Previously we have seen a dictonary called elements in which the element names are maped to their atomic numbers which are integers. But what if we want to store more information about each element like their atomic weight and symbol. We can do that by adjusting this dictionary so that it maps the element names to an other dictionary, that stores that collection of data.

In [ ]:

elements = {"hydrogen": {"number": 1, "weight": 1.00794, "symbol": "H"}, "helium": {"number": 2, "weight": 4.002602, "symbol": "He"}}

We can look up information about an element using this nested dictionary, using square brackets or the get() method.

In [ ]:

helium = elements["helium"] # get the helium dictionary hydrogen_weight = elements["hydrogen"]["weight"] # get hydrogen's weight print(helium) print(hydrogen_weight)

You can also add a new key to the element dictionary.

In [ ]:

oxygen = {"number":8,"weight":15.999,"symbol":"O"} # create a new oxygen dictionary elements["oxygen"] = oxygen # assign 'oxygen' as a key to the elements dictionary print('elements = ', elements)

Question:

Try your hand at working with nested dictionaries. Add another entry, 'is_noble_gas,' to each dictionary in the elements dictionary. After inserting the new entries you should be able to perform these lookups:


print(elements['hydrogen']['is_noble_gas'])

False

print(elements['helium']['is_noble_gas'])

True

In [ ]:

elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'}, 'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}} # todo: Add an 'is_noble_gas' entry to the hydrogen and helium dictionaries # hint: helium is a noble gas, hydrogen isn't elements['helium']['is_noble_gas'] = True elements['hydrogen']['is_noble_gas'] = False

In [ ]:

elements

In [ ]: