From c888f7099340fe2eb3fce6993f91d8ded1c9f1b0 Mon Sep 17 00:00:00 2001 From: Anshuman Rout Date: Sat, 1 Oct 2022 15:30:11 +0530 Subject: [PATCH 1/2] added list comprehension and list slicing --- python.md | 47 +++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/python.md b/python.md index a03b50d..4a9a002 100644 --- a/python.md +++ b/python.md @@ -58,10 +58,10 @@ In Python, declaring variables is not required. Means you don't need to specify ```py # declaring a function -def function-name(parameters){ # here parameters are optional - #code -} -function-name(parameters); # calling a function +def function-name(parameters) # here parameters are otional + pass + +function-name(parameters) # calling a function ``` ## Collections @@ -88,6 +88,45 @@ print(mylist[-1]) # prints Samsung |lst.sort()| sort the given list items| |lst.reverse() |reverse the given list items| +#### list comprehension +```py +# instead of populating list like this +l = list() +for i in range(100): + l.append(i) +# you can do this in one liner +l = [x for x in range(100)] +# one more example +# suppose you want to create a list of even numbers from +# 1 to 100 +evennums = [x if x%2==0 for x in range(100)] +``` +#### list slicing +```py +# suppose there is a list and you wanna access only +# certain subarray +subarr = arr[2:5] +# subarr is the subarray of arr from 2 to 4 considering 0 based index +subarr1 = arr[:5] +subarr2 = arr[2:] +# if nothing is given in the left of colon , the default accepted is 0 +# if nothing is given in right , the default is accepted as len(arr)-1 + + +# accessing from backword +# let n be an natural number +# where n can't be 0 +ele = arr[-n] +# ele is the element in the arr[len(arr)-n] +ele = arr[-x:-n] +# ele is the subarray of arr from arr[len(arr)-x] to arr[len(arr)-n] + +# suppose you wanna access some perticular indexes + +ele = arr[2:8:2] +# ele gives the subsequence of arr starting from index 2 to index 7 but only iterates over even position +``` + ### 2. Tuple Tuple is ordered collection of items and can't be changed. `()` are used to represent Tuples. From a5c78bbdb0a9efeaffcd1b99ddee0ec74c709696 Mon Sep 17 00:00:00 2001 From: Anshuman Rout Date: Sat, 1 Oct 2022 16:00:04 +0530 Subject: [PATCH 2/2] added : to the function defination --- python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.md b/python.md index 4a9a002..f017d6e 100644 --- a/python.md +++ b/python.md @@ -58,7 +58,7 @@ In Python, declaring variables is not required. Means you don't need to specify ```py # declaring a function -def function-name(parameters) # here parameters are otional +def function-name(parameters): # here parameters are otional pass function-name(parameters) # calling a function