fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,149 @@
---
title: Lists
---
**TODO: `list` basic info**
[Python Docs - Lists](https://docs.python.org/3/library/stdtypes.html#lists)
**Creation:**
An empty `list` is created using a pair of square brackets:
```shell
>>> empty_list = []
>>> type(empty_list)
<class 'list'>
>>> len(empty_list)
0
```
A `list` can be created with elements by enclosing a comma separated list of elements with square brackets. Lists allow for the elements to be of different types (heterogeneous) but are most commonly of a single type (homogeneous):
```shell
>>> homogeneous_list = [1, 1, 2, 3, 5, 8]
>>> type(homogeneous_list)
<class 'list'>
>>> print(homogeneous_list)
[1, 1, 2, 3, 5, 8]
>>> len(homogeneous_list)
6
>>> heterogeneous_list = [1, "Hello Campers!"]
>>> print(heterogeneous_list)
[1, "Hello Campers!"]
>>> len(heterogeneous_list)
2
```
The `list` constructor can also be used to create a `list`:
```shell
>>> empty_list = list() # Creates an empty list
>>> print(empty_list)
[]
>>> list_from_iterable = list("Hello campers!") # Creates a list from an iterable.
>>> print(list_from_iterable)
['H', 'e', 'l', 'l', 'o', ' ', 'c', 'a', 'm', 'p', 'e', 'r', 's', '!']
```
**Accessing elements of a `list`:**
```shell
>>> my_list = [1, 2, 9, 16, 25]
>>> print(my_list)
[1, 2, 9, 16, 25]
```
_Zero indexed_
```shell
>>> my_list[0]
1
>>> my_list[1]
2
>>> my_list[2]
9
```
_Wrap around indexing_
```shell
>>> my_list[-1]
25
>>> my_list[-2]
16
```
_Unpacking lists for python-3_
```shell
>>> print(*my_list)
1 2 9 16 25
```
_unpacking elements from the list to variables python-3_
We can unpack the elements of the list, and assign to variables.
```
>>> my_list = [2, 4, 6, 8]
>>> a, b, c, d = my_list
>>>print(a, b, c, d)
2 4 6 8
```
Same way, if we add * before the var name, this will automatically take the left elements of the list
```
>>> my_list = [2, 4, 6, 8, 10]
>>>a, *b = my_list
>>>print(a, b)
2 [4, 6, 8, 10]
```
Also, we can do this:
```
>>> my_list = [2, 4, 6, 8, 10]
>>>a, *b, c = my_list
>>>print(a, b, c)
2 [4, 6, 8] 10
```
**Reverse a `list`:**
```shell
>>> my_list = [1, 2, 9, 16, 25]
>>> print(my_list[::-1])
[25, 16, 9, 2, 1]
```
**Slice a `list`:**
```shell
>>> my_list = [1, 2, 9, 16, 25]
>>> print(my_list[:-2]) #Access sub-elements first to length-2
[1, 2, 9]
>>> print(my_list[2:]) #Access sub-elements 3rd to last element
[9, 16, 25]
>>> print(my_list[::2]) #Access list by skipping 2 indexes
[1, 9, 25]
```
**Mutable:**
`lists` are mutable containers. Mutable containers are containers that allow changes to which objects are contained by the container. **TODO: ADD MORE?**
_Re-arranging elements in a list_
Elements from a `list` may be extracted and re-arranged using another `list` as index.
```shell
>>> my_list = [1, 2, 9, 16, 25, 34, 53, 21]
>>> my_index = [5, 2, 0]
>>> my_new_list = [my_list[i] for i in my_index]
>>> print(my_new_list)
[34, 9, 1]
```
**TODO: Which of these should be discussed here:**
[Python Docs - More on Lists](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
* `list.append(x)` Add an item to the end of the list. Equivalent to a[len(a):] = [x].
* `list.extend(L)` Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.
* `list.insert(i, x)` Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
* `list.remove(x)` Remove the first item from the list whose value is x. It is an error if there is no such item.
* `list.pop([i])` Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
* `list.clear()` Remove all items from the list. Equivalent to del a[:].
* `list.index(x)` Return the index in the list of the first item whose value is x. It is an error if there is no such item.
* `list.count(x)` Return the number of times x appears in the list.
* `list.sort(key=None, reverse=False)` Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
* `list.reverse()` Reverse the elements of the list in place.
* `list.copy()` Return a shallow copy of the list. Equivalent to a[:].

View File

@ -0,0 +1,26 @@
---
title: List Append Method
---
## List Append Method
There are many methods for lists, you can explore all of them by typing `help(list)` in your python console.
One of them is the append function which, as the name says appends the argument given list.
#### Example Usage
```py
words = ["I", "love", "Python"]
words.append("very much")
print(words)
```
#### Output
```
["I", "love", "Python", "very much"]
```
As you might have noticed the element `"very much"` is appended to the list.
#### More Information:
The official documentation for `append()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>

View File

@ -0,0 +1,113 @@
---
title: List Comprehension
---
## List Comprehension
List Comprehension is a way of looping through a list to produce a new list based on some conditions. It can be confusing at first but once you are acclimated to the syntax it is very powerful and quick.
The first step in learning how to use list comprehension is to look at the traditional way of looping through a list. The following is a simple example that returns a new list of even numbers.
```python
# Example list for demonstration
some_list = [1, 2, 5, 7, 8, 10]
# Empty list that will be populate with a loop
even_list = []
for number in some_list:
if number % 2 == 0:
even_list.append(number)
# even_list now equals [2, 8, 10]
```
First a list is created with some numbers. You then create an empty list that will hold your results from the loop. In the loop you check to see if each number is divisible by 2 and if so you add it the the even_list. This took 5 lines of code not including comments and white space which isn't much in this example.
Now for the list comprehension example.
```python
# Example list for demonstration
some_list = [1, 2, 5, 7, 8, 10]
# List Comprehension
even_list = [number for number in some_list if number % 2 == 0]
# even_list now equals [2, 8, 10]
```
Another example, with the same two steps:
The following will create a list of numbers that correspond to the numbers in ```my_starting_list``` multiplied by 7.
```py
my_starting_list = [1, 2, 3, 4, 5, 6, 7, 8]
my_new_list = []
for item in my_starting_list:
my_new_list.append(item * 7)
```
When this code is run, the final value of ```my_new_list``` is:
```[7, 14, 21, 28, 35, 42, 49, 56]```
A developer using list comprehension could achieve the same result using the following list comprehension, which results in the same ```my_new_list```.
```py
my_starting_list = [1, 2, 3, 4, 5, 6, 7, 8]
my_new_list = [item * 7 for item in my_starting_list]
```
A simple formula to write in a list comprehension way is:
``` my_list = [{operation with input n} for n in {python iterable}]```
Replace ```{operation with input n}``` with however you want to change the item returned from the iterable. The above example uses ```n * 7``` but the operation can be as simple or as complex as necessary.
Replace ```{python iterable}``` with any iterable. [Sequence types](https://guide.freecodecamp.org/python/sequence-types) will be most common. A list was used in the above example, but tuples and ranges are also common.
List comprehension adds an element from an existing list to a new list if some condition is met. It is neater, but is also much faster in most cases. In some cases, list comprehension may hinder readability, so the devloper must weigh their options when choosing to use list comprehension.
## Examples of List Comprehension with Conditionals
The flow of control in list comprehensions can be controlled using conditionals. For exmaple:
```py
only_even_list = [i for i in range(13) if i%2==0]
```
This is equivalent to the following loop:
```py
only_even_list = list()
for i in range(13):
if i%2 == 0:
only_even_list.append(i)
```
List comprehension can also contain nested if conditions. Consider the following loop:
```py
divisible = list()
for i in range(50):
if i%2 == 0:
if i%3 == 0:
divisible.append(i)
```
Using list comprehension this can be written as:
```py
divisible = [i for i in range(50) if i%2==0 if i%3==0]
```
If-Else statement can also be used along with list comprehension.
```py
list_1 = [i if i%2==0 else i*-1 for i in range(10)]
```
#### More Information:
[Python Data Structures - Lists](https://docs.python.org/2.7/tutorial/datastructures.html)
[Python For Loops](https://guide.freecodecamp.org/python/for-loop-statements)
[Python Lists](https://guide.freecodecamp.org/python/learn-about-python-lists)
[Python For Beginners - List Comprehensions](http://www.pythonforbeginners.com/basics/list-comprehensions-in-python)

View File

@ -0,0 +1,25 @@
---
title: List Extend Method
---
## List Extend Method
There are many methods for lists, you can explore all of them by typing `help(list)` in your python console.
One of them is the extend function which, as the name says extends the list by adding all items of a list (passed as an argument) to the end.
#### Example Usage
```py
cities = ["San Francisco", "Los Angeles", "New York"]
cities_in_texas = ["San Antonio", "Austin", "Dallas"]
cities.extend(cities_in_texas)
print(cities)
```
#### Output
```
["San Francisco", "Los Angeles", "New York", "San Antonio", "Austin", "Dallas"]
```
#### More Information:
The official documentation for `extend()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>

View File

@ -0,0 +1,58 @@
---
title: List Index Method
---
## List Index Method
Among the many functions which come along with the list data structure the `index()` returns the the first occurrence/index of the element in the list given as an argument to the function.
Lists are the most basic Python data structure and stores a list of values in order (in comparison to dictionaries, which order doesn't matter). We retrieve the items by numerical index.
Keeping in mind the fact that indexing starts from 0, or the first element is taken to be at the 0 index, let's have a look at some examples.
#### Example Usage:
```py
numbers = [1, 2, 2, 3, 9, 5, 6, 10]
words = ["I", "love", "Python", "I", "love"]
print(numbers.index(9))
print(numbers.index(2))
print(words.index("I"))
print(words.index("am"))
```
##### Output:
```py
4
1
0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'am' is not in list
```
Here the first output is very obvious, but the second and third might seem confusing at first.But remember `index()` returns the first occurrence of the element and hence in this case `1` and `0` are the indices where `2` and `"I"` occur first in the lists respectively.
Also, if an element is not found in the list, a `ValueError` is returned as in the case of indexing `"am"` in the `words` list.
#### Optional arguments:
You can also use optional arguments to limit your search to a particular subsequence of the list as illustrated by this example:
```py
words = ["I","am", "a", "I", "am", "Pythonista"]
print(words.index("am",2,5))
```
##### Output:
```
4
```
Here although the element is searched between the indices 2(inclusive) and 5(not inclusive) but the returned index is computed relative to the beginning of the full list rather than the start argument.
#### More Information:
The official documentation for `index()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>

View File

@ -0,0 +1,99 @@
---
title: Map, Reduce, Filter
---
#Map,Reduce & Filter
Most engineers work with lists to process list of orders/users etc. Analyzing lists can get complex and cluttered quickly if using multiple for-loops and nested loops. Hence these above methods can streamline usage of list operations.
## Map
If your task is to apply a specific method to each element of a list, map will come in handy. Say, you have a list of degree values and you'd like to convert all these values into list of values in Fahrenheit units.
#### Example Usage
```py
inputs = [10,32,5,40,25]
def degreesToFahren(deg):
fahrenheit = (9.0/5)*deg +32
return fahrenheit
# The most common way of doing this
result=[]
for i in inputs:
iTofahren = degreesToFahren(i)
result.append(iTofahren)
print(result) # [50.0, 89.6, 41.0, 104.0, 77.0]
```
```py
# Using Map
result = list(map(degreesToFahren,inputs))
print(result) # [50.0, 89.6, 41.0, 104.0, 77.0]
```
As you might have noticed, using map is simply a one liner operation. Generally, if you have data = ``` [a1,a2,...,an] ``` and a function ``` f()```, then ``` map(f,data): ```returns an iterator over ```f(a1),f(a2)...f(an). ``` use ```list()``` to convert the iterator object into a python list.
## Filter
Filter function removes data in a list that you need/don't need , hence the name. Say, you want to filter a list based on values that you don't need, eg values above 2.
#### Example Usage
```py
data = [1.2,2.5,5.8,0.4,4.7,9.9]
result = list(filter(lambda x:x > 2,data))
print(result)
```
#### Output
```
[2.5, 5.8, 4.7, 9.9]
```
This is also a simple 1 liner similar to the map() function above. Refer to tutorial on lambda functions if you find this term unfamiliar.
## Reduce
From creator of Python, Guido van Rossum
```"Use functools.reduce if you really need it; however, 99% of the time an explicit for loop is more readable"```
What it generally does is apply a function ```f()``` to elements of data in a list and use that result for the next value in the list.
Visually,
Data = [a<sub>1</sub>,a<sub>2</sub>,...,a<sub>n</sub>]
function = f(x,y)
reduce(f,data):
Step 1: val<sub>1</sub> = f(a<sub>1</sub>,a<sub>2</sub>)
Step 2: val<sub>2</sub> = f(val<sub>1</sub>,a<sub>3</sub>)
Step 3: val<sub>3</sub> = f(val<sub>2</sub> ,a<sub>4</sub>)
.
.
.
Step n-1: val<sub>n-1</sub> = f(val<sub>n-2</sub>,a<sub>n</sub>)
For example, you want to multiply all numbers in a list.
#### Example Usage
```py
from functools import reduce
input = [1,2,3,4,5,6]
multiplier = lambda x,y:x*y
answer = reduce(multiplier,input)
print(answer)
```
#### Output
```
720
```
However, the above could be computed using a simple for loop and usage of these methods are subject to preference.
#### More Information:
The official documentation for the above methods can be found at http://book.pythontips.com/en/latest/map_filter.html

View File

@ -0,0 +1,41 @@
---
title: List Pop Method
---
# Pop Function
The method pop() removes and returns last element from the list. There is an optional parameter, index of the element to be removed from the list.
If no index is specified, a.pop() removes and returns the last item in the list.
If the index passed to the pop() method is not in the range, it throws IndexError: pop index out of range exception.
#### Example Usage
```py
cities = ['New York', 'Dallas', 'San Antonio', 'Houston', 'San Francisco'];
print "City popped is : ", cities.pop()
print "City at index 2 is : ", cities.pop(2)
```
#### Output
```
City popped is : San Francisco
City at index 2 is : San Antonio
```
#### Basic Stack Functionality
The `pop()` method is often used in conjunction with `append()` to implement basic stack functionality in a Python application.
```py
stack = []
for i in range(5):
stack.append(i)
while len(stack):
print(stack.pop())
```
#### More Information:
The official documentation for `pop()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>

View File

@ -0,0 +1,38 @@
---
title: List Remove Method
---
## List Remove Method
The `remove()` method removes the argument given to it from the list.
#### Example Usage
```py
words = ["I", "love", "Python"]
words.remove("I")
print(words)
```
#### Output
```py
["love","Python"]
```
Note that it returns an error if the element to be removed is not found in the list as illustrated in the example below.
```py
kiss = ["keep", "it", "simple", "stupid"]
kiss.remove("complex")
print(kiss)
```
#### Output
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
```
#### More Information:
More information about `remove()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>

View File

@ -0,0 +1,116 @@
---
title: List Sort Method
---
## List Sort Method
Python lists have a built-in ```sort()``` method that modifies the list in-place and a ```sorted()``` built-in function that builds a new sorted list from an iterable.
list.sort(key=…, reverse=[True/False])
### Parameters
There are two optional parameters to this method
<br><br>
<i>key</i> - The input value for the key parameter should be a function that takes a single argument and returns a value used for comparisons to sort the items in the list.
<br><br>
<i>reverse=[value]</i>
<br>
<i>value=True</i> : Sorts the items in the list in descending order.
<br>
<i>value=False</i> : Sorts the items in the list in ascending order. This is considered the default value.
<br><br>
Please note that the `sort()` method does not return any value. It modifies the original list.
### Example Usage
```py
a = [4, 2, 5, 3, 1]
a.sort()
print a # prints [1, 2, 3, 4, 5]
b = ['free', 'code', 'camp']
b.sort()
print b # prints ['camp', 'code', 'free']
```
Consider an example with the <b>reverse</b> parameter:
```py
a = [4, 2, 5, 3, 1]
#Sorts the list in descending order
a.sort(reverse=True)
print a # prints [5, 4, 3, 2, 1]
```
If you want to sort the list based on your own function, then use the <b>key</b> parameter.
<br>Here is an example to sort the strings in the list by length, in ascending order:
```py
a = ["hello", "hi", "hey"]
#The built-in len() function is given as an input to key parameter to sort the strings by length
a.sort(key = len)
print a # prints ['hi', 'hey', 'hello']
```
Here is another example, where the list contains tuples(name, age). <br>The usage below shows how to sort the list by age, in ascending order:
```py
#Consider the second element in the tuple for sorting
>>> def compareByAge(element):
... return element[1]
b = [('Adam', 20), ('Rahman', 30), ('Rahul', 25)]
#Sort the list by age
b.sort(key = compareByAge)
#Output
print b # prints [('Adam', 20), ('Rahul', 25), ('Rahman', 30)]
```
### Sorting Basics
A simple ascending sort is very easy -- just call the sorted() function. It returns a new sorted list:
```python
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
```
You can also use the list.sort() method of a list. It modifies the list in-place (and returns None to avoid confusion). Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient:
```python
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
```
Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable:
```python
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]
```
#### Implementation Details
If one wants to know details about the implementation of the sort function, the algorithm, and the time complexity, etc, refer <a href='http://svn.python.org/projects/python/trunk/Objects/listsort.txt' target='_blank' rel='nofollow'>here</a>. In brief, sort function uses TimSort algorithm, which according to Python Developers, is :-
>an adaptive, stable, natural mergesort, modestly called
timsort (hey, I earned it <wink>). It has supernatural performance on many
kinds of partially ordered arrays (less than lg(N!) comparisons needed, and
as few as N-1), yet as fast as Python's previous highly tuned samplesort
hybrid on random arrays.
#### sort() Parameters
By default, sort() doesn't require any extra parameters. However, it has two optional parameters:
* reverse - If true, the sorted list is reversed (or sorted in Descending order).
* key - A function that serves as a key for the sort comparison.
#### More Information:
More information about ```sort()``` can be found <a href='https://docs.python.org/3/library/functions.html#sorted' target='_blank' rel='nofollow'>here</a>.
More information about sort() and sorted() can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>.
More information about sort() and sorted() can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>.