Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
120 views

Python E1 Notes

This document provides examples of Python lists, tuples, and dictionaries. It demonstrates reversing lists, slicing lists with negative indexes, modifying lists by reference, deleting elements from lists and tuples, defining single element tuples, joining and multiplying tuples, accessing dictionary keys, values, and items, copying and deleting dictionaries, updating dictionaries by merging keys and values from multiple dictionaries, and converting a tuple of key-value pairs to a dictionary. The key differences between lists and tuples are that lists are mutable while tuples are immutable, and tuples can be used as dictionary keys while lists cannot.

Uploaded by

aniket
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Python E1 Notes

This document provides examples of Python lists, tuples, and dictionaries. It demonstrates reversing lists, slicing lists with negative indexes, modifying lists by reference, deleting elements from lists and tuples, defining single element tuples, joining and multiplying tuples, accessing dictionary keys, values, and items, copying and deleting dictionaries, updating dictionaries by merging keys and values from multiple dictionaries, and converting a tuple of key-value pairs to a dictionary. The key differences between lists and tuples are that lists are mutable while tuples are immutable, and tuples can be used as dictionary keys while lists cannot.

Uploaded by

aniket
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

1.

SPACE HAS HIGHER VALUE LEXICOGRAPHICAL

a = "A"
b = "B"
c = "C"
d = " "

lst = [a, b, c, d]
lst.reverse()

print(lst) -----------> [' ' ,'C' ,'B','A']

2. SLICING WITH NEGATIVE INDEXES


my_list = [10, 8, 6, 4, 2]
new_list = my_list[1:-1]
print(new_list) ---------------------> [8,6,4]

3. LIST ARE DYNAMICALLY MODIFIED AND ARE REFERENCED

list_1 = ["A", "B", "C"]


list_2 = list_1
list_3 = list_2

del list_1[0]
del list_2[0]

4. list_1 = ["A", "B", "C"]


list_2 = list_1
list_3 = list_2

del list_1[0]
del list_2

print(list_3)

Check
['B', 'C']

5. list_1 = ["A", "B", "C"]


list_2 = list_1
list_3 = list_2

del list_1[0]
del list_2[:]

print(list_3)

Check
[]
6. nums=[1,2,3]
print(nums[-1:-2]) -----------------------> []

7. def hi():
print("hi")

hi(5)

Check
An exception will be thrown (the TypeError exception to be more precise) - the hi()
function doesn't take any arguments

8. KEYWORD PASSING

def introduction(first_name, last_name):


print("Hello, my name is", first_name, last_name)

introduction(first_name = "James", last_name = "Bond")


introduction(last_name = "Skywalker", first_name = "Luke")

THIS IS NOT ALLOWED _


def introduction(first_name, last_name):
print("Hello, my name is", first_name, last_name)

introduction(surname="Skywalker", first_name="Luke")

print(list_3)-----------------> ['C']

8.

It's important to remember that positional arguments mustn't follow keyword


arguments. That's why if you try to run the following snippet:

def subtra(a, b):


print(a - b)

subtra(5, b=2) # outputs: 3


subtra(a=5, 2) # Syntax Error

9. print(None + 2)

will cause a runtime error, described by the following diagnostic message:

TypeError: unsupported operand type(s) for +: 'NoneType' and '

10.
def strange_function(n):
if(n % 2 == 0):
return True
print(strange_function(1)) ---------------------------------------------> None

11. Look at the difference in output in the following two examples:

# Example 1
def wishes():
print("My Wishes")
return "Happy Birthday"

wishes() # outputs: My Wishes

# Example 2
def wishes():
print("My Wishes")
return "Happy Birthday"

print(wishes())

# outputs: My Wishes
# Happy Birthday

12.
def message(number):
print("Enter a number:", number)

number = 1234
message(1)
print(number)

A situation like this activates a mechanism called shadowing:

parameter x shadows any variable of the same name, but...


... only inside the function defining the parameter.
The parameter named number is a completely different entity from the variable named
number.

OUTPUT
Enter a number: 1
1234

13. YOU CHECK IF A FXN IS RETURNING ANYTHING USING NONE

value = None
if value is None:
print("Sorry, you don't carry any value")

14.

The data type we want to tell you about now is a tuple. A tuple is an immutable
sequence type

15 . Defining tuples when you have single element in a tuple

If you want to create a one-element tuple, you have to take into consideration the
fact that, due to syntax reasons (a tuple has to be distinguishable from an
ordinary, single value), you must end the value with a comma:

one_element_tuple_1 = (1, )
16.

The similarities may be misleading - don't try to modify a tuple's contents! It's
not a list!

All of these instructions (except the topmost one) will cause a runtime error:

my_tuple = (1, 10, 100, 1000)

my_tuple.append(10000)
del my_tuple[0]
my_tuple[1] = -10

17. the + operator can join tuples together (we've shown you this already)
the * operator can multiply tuples, just like lists;

EXAMPLE
my_tuple = (1, 10, 100)

t1 = my_tuple + (1000, 10000)


t2 = my_tuple * 3

OUTPUT
t1=(1, 10, 100, 1000, 10000)
t2=(1, 10, 100, 1, 10, 100, 1, 10, 100)

18 .

dict.keys() gives all the keys of the dictionary named dict


dict.values() gives all the values of the dictionary named dict

19.

dict.items() ----> gives the elements of the dict that is both key value pair

EXAMPLE
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}

for english, french in dictionary.items():


print(english, "->", french)

20. Deleting a key - cause values associated with it to be removed

del dictionary['dog']

21. To copy a dictionary, use the copy() method:

pol_eng_dictionary = {
"zamek": "castle",
"woda": "water",
"gleba": "soil"
}

copy_dictionary = pol_eng_dictionary.copy()

22. You can use the del keyword to remove a specific item, or delete a dictionary.
To remove all the dictionary's items, you need to use the clear() method:

EXAMPLE
pol_eng_dictionary = {
"zamek": "castle",
"woda": "water",
"gleba": "soil"
}

print(len(pol_eng_dictionary)) # outputs: 3
del pol_eng_dictionary["zamek"] # remove an item
print(len(pol_eng_dictionary)) # outputs: 2

pol_eng_dictionary.clear() # removes all the items


print(len(pol_eng_dictionary)) # outputs: 0

del pol_eng_dictionary # removes the dictionary

23. Write a program that will "glue" the two dictionaries (d1 and d2) together and
create a new one (d3).

d1 = {'Adam Smith': 'A', 'Judy Paxton': 'B+'}


d2 = {'Mary Louis': 'A', 'Patrick White': 'C'}
d3 = {}

for item in (d1, d2):


# Write your code here.

print(d3)

Check
Sample solution:
d1 = {'Adam Smith': 'A', 'Judy Paxton': 'B+'}
d2 = {'Mary Louis': 'A', 'Patrick White': 'C'}
d3 = {}

for item in (d1, d2):


d3.update(item)

print(d3)

24. DICTIONARY ARE NOT REFERENCED IT SEEMS

What will happen when you run the following code?

my_dictionary = {"A": 1, "B": 2}


copy_my_dictionary = my_dictionary.copy()
my_dictionary.clear()

print(copy_my_dictionary)

Check
The program will print {'A': 1, 'B': 2} to the screen.

25.
Write a program that will convert the colors tuple to a dictionary.
colors = (("green", "#008000"), ("blue", "#0000FF"))

# Write your code here.

print(colors_dictionary)

Check
Sample solution:
colors = (("green", "#008000"), ("blue", "#0000FF"))

colors_dictionary = dict(colors)
print(colors_dictionary)

You might also like