Vector Equality and Identity
Lesson 8 of 48 in Coddy's Python for R Developers course.
R equality on atomic vectors is elementwise and may recycle operands. identical asks a stricter whole-object value-and-type question; it is not generally a pointer-identity query. Python list equality produces one boolean from element comparisons, while is asks whether references denote the same object. Separate equal lists are not identical. R all can reduce a logical equality vector, but missing values require a policy. Python built-in lists do not recycle operands to compare lengths. Avoid porting R identical mechanically to Python is: equal separately created values often satisfy the former but not the latter.
R
a <- c(1, 2)
b <- c(1, 2)
cat(a == b, "\n")
cat(identical(a, b), "\n", sep="")Python
a = [4]
b = [4]
print(a == b)
print(a is b)Porting trap
Use Python equality for values and identity only when identity matters, especially the None singleton. R identical and Python is answer different questions.
Challenge
BeginnerRead two text labels on separate lines. The reserved token missing means an absent label; all other lines, including an empty line, are actual strings. The scaffold converts that token to None. Print whether the labels have equal values, then whether the first is absent, then whether the second is absent, one Python boolean per line.
Print only these lines, ending each with a newline. Keep the supplied input scaffold; it reads the stated values without prompts.
Your code goes in main.py. The locked driver.py starts your program and cannot be edited.
Try it yourself
# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module
run_module("main", run_name="__main__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler