Posts

Showing posts with the label Python(Basics)

What is the difference between list method extend() and operators + or += in Python

Image
  In Python, list support + and += operators. They could do the same thing as the method extend(). extend(): iterate through the iterable object and append each element from the iterable to the end of the list to be extended. Its parameter could be any iterable. >>> a = ['a','b','c'] >>> b = ['x','y','z'] >>> a.extend(b) >>> a ['a', 'b', 'c', 'x', 'y', 'z'] + operator: instead of extending the list in place, it creates a new list leaving original list untouched; it is not as effcient as two others.  >>> a = ['a','b','c'] >>> b = ['x','y','z'] >>> c = a + b >>> c ['a', 'b', 'c', 'x', 'y', 'z'] += operator: it extends the list in place which is the same as the extend() method. >>> a = ['a','b','c...

The difference of list methods between append() and extend() in Python

Image
  Python lists are mutable, you can add objects to the list in place. Both append() and extend() methods could do the trick. append(): add a single object to the end of the list >>> l = ['a', 'b', 'c'] >>> l.append(['d','e','f']) >>> l ['a', 'b', 'c', ['d', 'e', 'f']] extend(): add all the elements from the iterable to the end of the list >>> l.extend(['d','e','f']) >>> l ['a', 'b', 'c', 'd', 'e', 'f']

How to use a global variable in a Python function

Image
In python, you could use global keyword to declare a variable inside a function as a global variable, such as: >>> global_var = 0 >>> def fun1(): global_var = 10 # global_var as local var print(global_var) >>> def fun2(): global global_var # declare global_var to be a global var global_var = 5 print(global_var) >>> print(global_var) 0 >>> fun1() 10 >>> print(global_var) 0 >>> fun2() 5 >>> print(global_var) 5 We define a global_var outside functions. Inside f un1() we define a local global_var without declaring it as global . Although it has the same name as the global_var outside the function, it is totally isolated from the gobal variable-- global_var . Inside fun2() , we declare global_var as a global variable, so it becomes global .  First, we print global_var , it is 0. Then invoke fun1() , it prints the result of the local variable global_var . We then check the value of global_var , it is...

How to check a list is empty or not in Python

Image
 The pythonic way to do this is: l = [] #A empty list is evalutated to False in Python. if not l:      print('list empty')