NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

LISTS:
The list type is a container that holds a number of other objects, in a given order. The list type implements the sequence protocol, and also allows you to add and remove objects from the sequence. List literals are written within square brackets [ ].
syntax:
list_name=[expression,...]
e.g.:
a=[1,4,25,73,2,6]

LISTS AS A SEQUENCE:
A list fulfills all the conditions of a sequence as sequences allows us to store multiple values in an organized and efficient fashion. Lists act as a sequence coz they allow us to store multiple values in organized n efficient fashion.

TRAVERSING A LIST:
The values in the lists are stored according to index values. To traverse the list we use those index values.
e.g.: a=[3,5,35,6,7,9]
The indexing starts from 0. So to access '35' which is at 3rd position and index 2 we use:
print a[2]

LIST OPERATIONS:
1) Accessing List: list_name[index] OR list_name[start:stop] OR list_name[start:stop:step]
e.g.: a=[2,5,6,3,1,7]
print a[2]
print a[-2]
print a[2:4]
print a[-2:-4]
print a[1:5:2]
output:
6
1
6,3
1,3
5,1
2) Looping Over Lists:
The for-in statement makes it easy to loop over the items in a list:
eg: for item in L:
print item
3) Modifying lists:
Lists cn b modified using d index values.
eg:
a=[3,5,6]
a[1]=8
4) Deleting items:
del list_name[index]
5) Searching:
The "in" operator can be used to check if an item is present in the list:
eg:
if value in L:
print "list contains", value

To get the index of the first matching item, use index:
eg:
i = L.index(value)
To count matching items, use the count method:
eg:
n = L.count(value)
6) Sorting Lists
The sort method sorts a list in place.
L.sort()

LIST SLICES
Slice. A slice extracts elements, based on a start and stop.
eg:
values[1:3] Index 1 through index 3.
values[2:-1] Index 2 through index one from last.
values[:2] Start through index 2.
values[2:] Index 2 through end.
values[::2] Start through end, skipping ahead 2 places each time.

LIST METHODS:
1) cmp(list1, list2) Compares elements of both lists.
2) len(list) Gives the total length of the list.
3) max(list) Returns item from the list with max value.
4) min(list) Returns item from the list with min value.
5) list(seq) Converts a tuple into list.
6) list.append(obj) Appends object obj to list
7) list.count(obj) Returns count of how many times obj occurs in list
8) list.extend(seq) Appends the contents of seq to list
9) list.index(obj) Returns the lowest index in list that obj appears
10) list.insert(index, obj) Inserts object obj into list at offset index
11) list.pop(obj=list[-1]) Removes and returns last object or obj from list
12) list.remove(obj) Removes object obj from list
13) list.reverse() Reverses objects of list in place
14) list.sort([func]) Sorts objects of list, use compare func if given

MAP, FILTER AND REDUCE:
1) MAP: map() is a function with two arguments:
r = map(func, seq)
The first argument 'func' is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. It returns a new list with the elements changed by func.
eg:
>>> items = [1, 2, 3, 4, 5]
>>> def sqr(x): return x ** 2
>>> list(map(sqr, items))
[1, 4, 9, 16, 25]
>>>
2) FILTER: The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function function returns True.
The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True will the element of the list be included in the result list.
eg:
>>> list(range(-5,5))
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>>
>>> list( filter((lambda x: x < 0), range(-5,5)))
[-5, -4, -3, -2, -1]
>>>
3) REDUCE: The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value.
If seq = [ s1, s2, s3, ... , sn ], calling reduce(func, seq) works like this:
*At first the first two elements of seq will be applied to func, i.e. func(s1,s2) The list on which reduce() works looks now like this: [ func(s1, s2), s3, ... , sn ]
*In the next step func will be applied on the previous result and the third element of the list, i.e. func(func(s1, s2),s3)
*The list looks like this now: [ func(func(s1, s2),s3), ... , sn ]
*Continue like this until just one element is left and return this element as the result of reduce()
eg:
>>> reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
24
>>>
>>> L = ['Testing ', 'shows ', 'the ', 'presence', ', ','not ', 'the ', 'absence ', 'of ', 'bugs']
>>> functools.reduce( (lambda x,y:x+y), L)
'Testing shows the presence, not the absence of bugs'
>>>
DELETING ELEMENTS:
list_name.remove(obj)
This method does not return any value but removes the given object from the list.
eg:
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.remove('xyz');
print "List : ", aList
aList.remove('abc');
print "List : ", aList

output:
List : [123, 'zara', 'abc', 'xyz']
List : [123, 'zara', 'xyz']

LISTS AND STRINGS:
List- Set of integers, characters, strings etc.
String- Set of characters.
List- Elements can be updated.
String- Whole string can be changed but not the characters.
*Both can mutated and concatenated.
A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use 'list':
>>> s = 'spam'
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm']
Because list is the name of a built-in function, you should avoid using it as a variable name.
The list function breaks a string into individual letters. To break a string into words, use the split method:

>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']
>>> print t[2]
the

We can call split with an optional argument called a delimiter specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:

>>> s = 'spam-spam-spam'
>>> s.split('-')
['spam', 'spam', 'spam']

join is the inverse of split. It takes a list of strings and concatenates the elements.

>>> t = ['pining', 'for', 'the', 'fjords']
>>> join(t,' ')
'pining for the fjords'

In this case the glue element is a space character, so join puts a space between words. To concatenate strings without spaces, you can use the empty string, ", as a glue element.

OBJECTS AND VALUES:
Object is said to be an entity which can be uniquely identified with its set of attributes. And the attributes that define an objects are the values.
If we execute these assignment statements:
a = 'banana'
b = 'banana'
We know that a and b both refer to a string, but we don't know whether they refer to the same string. There are two possible states:
In one case, a and b refer to two different objects that have the same value. In the second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the is operator.
>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
In this example, Python only created one string object, and both a and b refer to it.
But when we create two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.
It is more precise to say that an object has a value. If we execute a = [1,2,3], a refers to a list object whose value is a particular sequence of elements. If another list has the same elements, we would say it has the same value.

ALIASING:
Aliasing describes a situation in which a data location in memory can be accessed through different names in the program. Thus, modifying the data through one name implicitly modifies the values associated with all aliased names.
If 'a' refers to an object and assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
The association of a variable with an object is called a reference.
An object with more than one reference has more than one name, so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 17
>>> print a
[17, 2, 3]
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem. In this example:
a = 'banana'
b = 'banana'
It almost never makes a difference whether a and b refer to the same string or not.

LIST ARGUMENTS:
The arguments passed in a function which are lists instead of variables are list arguments. The list may or may not get modified after the execution of the functions.
eg:
>>>def delete_head(t):
del t[0]
>>>
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']

DICTIONARIES:
A dictionary is like a list, but more general. In a list, the positions (indices) have to be integers; in a dictionary the indices can be (almost) any type.
Dictionary is a mapping between a set of indices (keys) and a set of values. Each key maps to a value. The association of a key and a value is called a key-value pair.
syntax:
dict_name={'key1':value1, 'key2':value2,...}
eg:
a={'apple':14, 'bat':54, 'fs':34}

DICTIONARY AS A SET OF COUNTERS:

['apple','red','apple','red','red','pear']
The simplest way to add the list items to a dictionary and count how many times the item appears in the list.
So for the list above I would like the output to be:
{'apple': 2, 'red': 3, 'pear': 1}
Dictionaries have a method called 'get' that takes a key and a default value. If the key appears in the dictionary, get returns the corresponding value; otherwise it returns the default value. For example:
>>> counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
>>> print counts.get('jan', 0)
100
>>> print counts.get('tim', 0)
0

Thus a dictionary acts as a set of counters as it contains values against specific keys where the values can act like counters for the keys.

LOOPING AND DICTIONARIES:
for-in loops can be used to traverse a dictionary. It traverses the keys of the dictionary.
This loop prints each key and the corresponding value:
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
for key in counts:
print key, counts[key]
output:
jan 100
chuck 1
annie 42

REVERSE LOOK UP:
Given a dictionary d and a key k, it is easy to find the corresponding value v = d[k]. This operation is called a lookup.But if we have v and want to find k. This is reverse lookup.
Here is a function that takes a value and returns the first key that maps to that value:
def reverse_lookup(d, v):
for k in d:
if d[k] == v:
return k

DICTIONARIES AND LISTS:
*Both are mutable.
*Lists are automatically indexed with integer values. Indexes in dictonaries can be user given and can be strings.
*Lists declared using [], Dictionary declared using {}.

MEMOS:
A previously computed value that is stored for later use is called a memo. Memos are usually seen in recursive function calls. When the function calls itself, the values after the function call get stored for later use after the recursive call ends after reaching the base case, those values are memos.

GLOBAL VARIABLES:
A global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. Unlike local variables, which disappear when their function ends, global variables persist from one function call to the next.

LONG INTEGERS:
Integers are used to store numeric values without decimal point, but the size of integer variables is not very big, so integers cannot store very large integer values. For very large integer values Long integers are used. Long integers are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.

TUPLES:
A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.
syntax:
tuple_name=(values,...)
eg:
a=(3,6,23,66)

TUPLE ASSIGNMENT:
Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an assignment to be assigned values from a tuple on the right of the assignment.
eg:
>>> m = [ 'have', 'fun' ]
>>> (x, y) = m
>>> x
'have'
>>> y
'fun'
>>>

TUPLES AS RETURN VALUES:
A function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. Functions can always only return a single value, but by making that value a tuple, we can effectively group together as many values as we like, and return them together.
eg:
def f(r):
c = 2 * math.pi * r
a = math.pi * r * r
b=(c,a)
return b

VARIABLE LENGTH ARGUMENT TUPLES:
Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple. For example, printall takes any number of arguments and prints them:

def printall(*args):
print args

Here’s how the function works:
>>> printall(1, 2.0, '3')
(1, 2.0, '3')

The complement of gather is scatter. If we have a sequence of values and want to pass it to a function as multiple arguments, we can use the * operator. For example, divmod takes exactly two arguments; it doesn’t work with a tuple:

>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1

But if we scatter the tuple, it works:

>>> divmod(*t)
(2, 1)

Thus, tuples can act as arguments of variable lengths.

LIST AND TUPLE:
zip is a built-in function that takes two or more sequences and “zips” them into a list of tuples where each tuple contains one element from each sequence. In Python 3, zip returns an iterator of tuples, but for most purposes, an iterator behaves like a list.

This example zips a string and a list:

>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a', 0), ('b', 1), ('c', 2)]

DICTIONARIES AND TUPLES:
Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair.

>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]

COMPARING TUPLES:
The relational operators work with tuples and other sequences; Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they are really big).

>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True

SEQUENCE OF SEQUENCE:
A sequence of sequence or nested sequences are possible in python.
1) List of lists:
eg:
>>>a=[[1,2],[5,3]]
>>>print a[1][1]
3
2) Dictionary of Dictionary:
eg:
>>>a={'d':{'f':9}, 'h':75}
>>>print a[d][f]
9
3) Tuple of tuple:
eg:
>>>a=(3,5)
>>>b=(7,8)
>>>c=(2,a,b)
>>>print c
(2,(3,5),(7,8))
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.