Wed 07 October 2015

Filed under Python

Slices

First: What is 'Slicing'? Slicing allows you to get a substring from a string. Or a portion of a list. That 'slice' is returned.

The syntax: sequence[start:end:step].
Or you can also think of it as sequence[from index: until index (not including): step]. Remember, Python uses a 0 index. See the docs

Direction

  • If the 'start' is absent or a positive number, then the 'start' is from the left; in other words - forward. If the 'start' is a negative number, then the 'start' index begins from the end.

  • If the 'end' is absent or a positive number, then the 'end' is from the left; in other words - forward. If the 'end' is a negative number, then the 'end' index begins from the end.

  • If the 'step' is absent or a positive number, then the 'start' is from the left; in other words - forward. If the 'step' is a negative number, then the 'start' is from the right, from the end; in other words - backward. (see examples below)

Defaults

  • If there is no 'start', then it begins from the beginning - depending on the direction.

  • If there is no 'end', then it goes until the end - depending on the direction.

  • If there is no 'step', then it goes one by one forward. If there is a 'step', then it counts that number, depending on the direction.


Some examples, using a string. And a list:

mystr = "ABCD"
mylist = ["a", "b", "c", "d"]
the code result explanation
mystr[0]
'A'
only the element in index 0
mylist[0]
'a'
only the element in index 0
mystr[1:]
'BCD'
start from index 1 until the end
mylist[1:]
['b', 'c', 'd']
start from index 1 until the end
mystr[:1]
'A'
start from index 0 until index 1
mylist[:1]
['a']
start from index 0 until index 1
mystr[1:3]
'B','C'
start from index 1 until index 3
mylist[1:3]
['b', 'c']
start from index 1 until index 3
mystr[1:6]
'B','C','D'
start from index 1 until index 6 (or until the highest index in the sequence)
mylist[1:6]
['b', 'c', 'd']
start from index 1 until index 6 (or until the highest index in the sequence)
mystr[1::2]
'B','D'
start from index 1 until index 6 (or until the highest index in the sequence), in step 2
mylist[1::2]
['b', 'd']
start from index 1 until index 6 (or until the highest index in the sequence), in step 2
mystr[-1]
'D'
start at the end, for 1 index (In other words, the last element)
mylist[-1]
['d']
start at the end, for 1 index (In other words, the last element)
mystr[:-1]
'ABC'
start at index 0, until 1 index starting from the end
mylist[:-1]
['a', 'b', 'c']
start at index 0, until 1 index starting from the end
mystr[2:2]
''
start at index 2, until index 2. (In other words, nothing - an empty string)
mylist[2:2]
[]
start at index 2, until index 2. (In other words, nothing - an empty list)
mystr[2:1]
''
start at index 2, until index 1. (Which cannot happen. In other words, nothing - an empty string)
mylist[2:1]
[]
start at index 2, until index 1. (Which cannot happen. In other words, nothing - an empty list)
mystr[-3:-1]
'BC'
start at 3rd to last index, until the 1st to last index
mylist[-3-1]
['b','c']
start at 3rd to last index, until the 1st to last index
mystr[::-1]
'DCBA'
start from the end - going backwards, until the beginning (In other words reversed).
mylist[::-1]
['d', 'c', 'b', 'a']
start from the end - going backwards, until the beginning (In other words reversed).
mystr[:]
'ABCD'
start from the beginning, until the end (In other words, a copy)
mylist[:]
['a', 'b', 'c', 'd']
start from the beginning, until the end (In other words, a copy)
mystr[2::-1]
'CBA'
start from the end - going backward, 2 indexes in, until the beginning
mylist[2::-1]
['c', 'b', 'a']
start from the end - going backward, 2 indexes in, until the beginning
mystr[2:1:-1]
'C'
start from the end - going backward, 2 indexes in, for 1 index
mylist[2:1:-1]
['c']
start from the end - going backward, 2 indexes in, for 1 index
del mystr[:]
'str' object does not support item deletion
del mylist[:]
[]
deletes the contents in the list, but not the actual list itself

A few more cool things with Slice

Sometimes, you might find it useful to separate the actual forming of the slice and the passing that slice definition to the actual sequence or list. You can do that with the built-in method slice. The syntax is a = slice(start, end, step) and then you can use it with the string or list - as mylist[a].

>>>a = slice(1, 5, 2)
>>>mylist[a] 
['b', 'd'] # start at index one, end at index 5, with step 2

>>>mystr[a]
'BD'

>>>a.start
1
>>>a.stop
5
>>>a.step
2

Conditional Start/ Stop/ Step You can use inline conditional statements* directly in the slice definition - for the 'start', 'stop' or 'step'. Note you can use None if you don't want to include the 'start', 'stop' or 'step'.

*Inline conditional statements are one-liner if statements. [See more] (http://www.deekras.com/if-else.html)

>>>i=True
>>>mylist[1 if i else 2]
'b'
>>>mylist[0: 2 if i else 3]
['a', 'b']
>>>mylist[::-1 if i else 1]
['d', 'c', 'b', 'a']


>>>i=2
>>>mystr[3: None if i <0 else i: -1]
'D'

Assignment

You can assign specified index with a new value. It deletes the elements in those indexes and inserts new values. - If no new values are provided, it just deletes the elements in those indexes.

  • If there are more elements to be assigned than those that are deleted, then those 'extra' elements are inserted right after those that did have a place to be inserted.

It actually changes the list; and does not return anything. (You'll have to call the list to see the actual change.) Note: Assignment does not work with strings.

the code result explanation
mylist[0] = "1"
['1', 'b', 'c', 'd']
assigns "1" in the 0 index
mylist[0] = "1", "2"
[('1', '2'), 'b', 'c', 'd']
assigns all into the 0 index
mylist[0:2] = "1"
['1', 'c', 'd']
is prepared to assign into the 0 index and the 1 index, so deletes those 2 elements. but only has 1 element to assign
mylist[0:2] = "1", "2"
['1', '2', 'c', 'd']
is prepared to assign into the 0 index and the 1 index, so deletes those 2 elements. and assigns the "1" and "2" to those indexes
mylist[0:1] = "12"
['1', '2', 'b', 'c', 'd']
is prepared to assign to the 0 index. it reads the string "12" as iterator, so places each element - the "1" and "2" in the iterator into the list - starting at the 0 index.
mylist[0:1] = "12",
['12', 'b', 'c', 'd']
is prepared to assign to the 0 index. it reads the string as an item in a tuple - notice the comma at the end. so places the "12" into the list - starting at the 0 index.
mylist[1:2] = []
['a', 'c', 'd']
is prepared to assign to the 1 index. There is nothing to assign, so essentially, it deletes that element.
mylist[:] = "1", "2", "3"
['1', '2', '3']
is prepared to assign to the entire list. And places the elements into the list - starting at the beginning
mylist[0:2] = ["1"]
['1', 'c', 'd']
mylist[0:2] = ["1","2", "3"]
['1', '2', '3', 'c', 'd']
mystr[0] = "1"
TypeError: 'str' object does not support item assignment

islice

islice is from the itertools library. It creates an iterator from the slice. This saves memory since the data is not produced from the iterator until it is needed. See the docs

>>>from itertools import islice, count

>>>islice(mylist, 0, 2)
<itertools.islice object at 0x7f00bf0937e0>

>>>list(islice(mylist, 0, 2))
['a', 'b']

>>>islice(mystr, 0, 2)
<itertools.islice object at 0x7f00bf0937e0>

>>>list(islice(mystr, 0, 2))
['A', 'B']

>>>for i in islice(count(), 0, 100, 10):
      print i,
0 10 20 30 40 50 60 70 80 90
Comment

Fri 29 May 2015

Filed under Python

namedtuple

I recently watched the most wonderful talk by Raymond Hettinger at Pycon 2015 about Pep8. Amongst many interesting and important points, he spoke about namedtuple that I believe he wrote. (It's toward the end of the talk at ~47:00). He posits that the namedtuple is one of ...

Read More

Thu 28 May 2015

Filed under Python

Timeit

A great library for testing the time of short code (a few short lines).

The syntax:

import timeit
timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)

timeit.repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)
- `stmt`: this is the statement that is ...
Read More

Mon 18 May 2015

Filed under Python

The regular if-else statements syntax:

if condition1:
    to_do_if_condition1_istrue
elif condition2:
    to_do_if_condition2_istrue
else:
    to_do_if_no_conditions_istrue

Some alternatives to the regular if-else statements.

Inline if-else

Everything is on one line.

expression_if_true if condition else expression_if_false

It looks at the condition.

  • If it is TRUE, then it does what is on the left.

  • If ...

Read More

Sat 31 January 2015

Filed under Python

Dictionaries

ways to create the dictionary

>>> d = dict(zip(('A','B','C'),(1,2,3)))
>>> d
{'A': 1, 'C': 3, 'B': 2}
>>> e = {}
>>> e['A']= 1
>>> e
{'A': 1}
>>> e['B']=2
>>> e
{'A': 1, 'B': 2}
>>> e['C']=3
>>> e
{'A': 1, 'C': 3, 'B': 2}
>>> e= {}
>>> zipped = zip ...
Read More

Wed 28 January 2015

Filed under Python

Strings

Here I share some cool things you can do with strings.

count(), len(), max(), min(),

>>> 'ababababbbbababab'.count('a')
7
>>> 'ababababbbbababab'.count('ab')
7
>>> 'ababababbbbababab'.count('bb')
2
>>> 'ababababbbbababab'.count('ab',6)
4
>>> 'ababababbbbababab'.count('ab',6,10)
1


>>> len('afhjcrnamwvsiytdr')
17
>>> max('afhjcrnamwvsiytdr')
'y'
>>> min('fhjcrnmwvsiytdr')
'c'

Syntax str ...

Read More

Tue 27 January 2015

Filed under Python

Sets

First: What is a 'set'?

In very short, a set is a collection with no duplicates.

For example: We have a list of names: names = ['Alice', 'Bill', 'Jane', 'Jack', 'Bill']. Bill is in that list twice. When we call set(names), we will get back that list with Bill ...

Read More

Mon 26 January 2015

Filed under Python

Filter

First: What is 'filter'?

In very short, filter runs the given function over the given iterable and only returns those that are true.

For example: We have a function that returns only those items in the list that are integers.

The Syntax

filter(function, iterable)

  • The function can be ...

Read More

Sun 25 January 2015

Filed under Python

Lambdas

First: What is 'lambda'?

In very short, lambda is a one-line, mini function. So we just include the short code directly into that line of code instead of writing out a separate function for it. If that mini function would be used in several places in the code, then ...

Read More

Map

Sun 25 January 2015

Filed under Python

Maps

First: What is 'map'?

In very short, map runs the given function over the given iterable.

For example: We have a function that converts years to their Roman numeral version. And we have a list of years. We can run a map(convert_year_to_roman_numeral, ['1999', '1776', '2015']. This will run ...

Read More

Sun 25 January 2015

Filed under Python

Reduce

First: What is 'reduce'?

In very short, reduce applies the function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. The left argument is the accumulated value and the right argument is the update value ...

Read More

Sun 18 January 2015

Filed under Python

Binary Search

First: What is a 'binary search'?

The task: search through a sorted list to find the specified value.

A linear search will start at the beginning and iterate through the list until it finds it. Depending on the size of the list and where in the list the ...

Read More

Sat 17 January 2015

Filed under Python

Working with linked lists:

First: What is a 'linked list'?

In very short, a linked list is comprised of nodes that are linked together to create a collection of nodes, in other words a list. The nodes reside anywhere in the memory, not necessarily one right after the other as ...

Read More

Mon 22 December 2014

Filed under Python

Moving along with SQLAlchemy and ... Relationships

Most of programming is not a simple flat table. Mostly, there are several tables, and there is something that links them - the tables have relationships.

So going back to the small membership program from the previous post, let's add a purchases table, where ...

Read More

Sat 20 December 2014

Filed under Python

First, why SQLAlchemy is powerful.

There's a whole set of features of SQLAlchemy listed in their docs. I have found that using SQLAlchemy instead of SQLlite has made it much easier to access the data, since data is saved as a class. And writing methods and queries on that ...

Read More

Thu 18 December 2014

Filed under Python

Recursions on lists .. with slices

Following up on my post about recursions. This time about recursive functions using a list.

So here's where slices gets really useful.

As a quick reminder about slices: Slices allow you to get a substring from a string or part of a list. The ...

Read More

Wed 17 December 2014

Filed under Python

So how do recursions work?

I hear so much about recursions. They're supposedly in all interview questions. So here's my attempt at trying to make them easy to understand.

A recursive function is a function that calls itself. I'll throw in a simple example. The factorial.

The ...

Read More

Tue 16 December 2014

Filed under Python

Decorators: Decorators - with *args and **kwargs

This post builds on my previous one about Decorators.

So we have the decorator that 'prettifies' the date returned from the original function.

def pretty_date(func):
    def wrapper():
        print 'getting the date from function: {}'.format(func.__name__)
        date = func()
        print 'got the date: {} (before ...
Read More

Mon 15 December 2014

Filed under Python

Decorators: a function within a function

Now a post about decorators. Decorators are quite useful - when you learn how to use them. Here's my attempt at making them easy easier to understand.

First, when might decorators be used?

Decorators are used to extend a function. To give it more ...

Read More

Sun 14 December 2014

Filed under Python

Working with Threads

I've been encouraged to learn sockets and threading. It's been fun. With some frustrating moments when the book I am using and the docs are just not clear enough - for me. So here I present it in a way that would have worked for me ...

Read More

Sat 13 December 2014

Filed under Python

Kinda cool to get the weather just the way I need it

Moving along in discussing some of features of the little application I wrote.

I already got the IP and then found the longitude and latitude coordinates based on that IP.

The next step is to find the local ...

Read More

Fri 12 December 2014

Filed under Python

Once I had the IP, I needed to find the longitude & latitude coordinates

On that recent project I was working on, I was looking for the local weather based on where the user is located. So first, I got the IP. With that IP, I used pygeoip.GeoIP to find ...

Read More

Thu 11 December 2014

Filed under Python

Here's how to get the IP

For a recent project, I needed to get the longitude and latitude of where the user was at the time. And from that data, I could get the local weather.

To do that, I'd find her local IP and then later use ...

Read More

DeeKras.com © Dee Kras Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More