15. Lists are ObjectsH.pdf - Comparing Lists 15 Lists are Objects You can use = to compare two lists Topics References Alias More on Slicing > x

# 15. Lists are ObjectsH.pdf - Comparing Lists 15 Lists are...

This preview shows page 1 - 4 out of 8 pages.

1 15. Lists are Objects Topics: References Alias More on Slicing Comparing Lists >>> x = [10,20,30,40] >>> y = [10,20,30,40] >>> x==y True You can use == to compare two lists Comparing Lists You can use == to compare two lists 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 y --> 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> The Boolean expression x==y is True because x and y have the same length and identical values in each element Comparing Lists >>> x = [1,2,3] >>> y = [1.0,2.0,3.0] >>> x==y True You can use == to compare two lists If there are ints and floats, convert everything to float then compare Comparing Lists >>> x = [10,20,30,40] >>> y = [11,21,31,41] >>> x<y True >>> y<x True Do not use <, <= , > , >= to compare two lists Unpredictable Aliasing x = [10,20,30,40] y = x This: 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> y --> Results in this:
2 Aliasing 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> y --> Things to say: x and y are variables that refer to the same list object. The object is aliased because it has more than one name. Tracking Changes x = [10,20,30,40] y = x y = [1,2,3] 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> Tracking Changes x = [10,20,30,40] y = x y = [1,2,3] 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> y --> Tracking Changes x = [10,20,30,40] y = x y = [1,2,3] 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> 0 ---> 1 1 ---> 2 2 ---> 3 y --> The is Operator >>> x = [10,20,30,40] >>> y = [10,20,30,40] >>> x is y False Even though the two lists have the same component values. x and y do not refer to the same object. 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 y --> The is Operator >>> x = [10,20,30,40] >>> y = x >>> x is y True x and y refer to the same object 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> y -->
3 Making a Copy of a List x = [10,20,30,40] y = list(x) 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> Making a Copy of a List x = [10,20,30,40] y = list(x) 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 y --> Slices Create new Objects x = [10,20,30,40] y = x[1:] 0 ---> 10 1 ---> 20 2 ---> 30 3 ---> 40 x --> Slices Create New Objects x = [10,20,30,40] y = x[1:] 0 ---> 10 1 ---> 20 2 ---> 30

#### You've reached the end of your free preview.

Want to read all 8 pages?

• Fall '19
• Harshad number, Void type, Parameter x