Tuple in Python

Tuples in Python are immutable sequences of random objects. Once created, the objects within them cannot be replaced or removed,and new elements cannot be added.

Tuples have a similar syntax to lists except that they are delimited by parentheses rather than square brackets.Here’s a literal tuple containing a string, a float, and an integer.
We can access the elements of a tuple by zero-based index using square brackets, and we can determine the number of elements in the tuple using the built-in len function. We can iterate over tuples using the for loop, and we can concatenate tuples using the plus operator.

ex1

Sometimes a single element tuple is required. To write this, we can’t just use a simple number in parentheses. This is because Python pauses that as an integer enclosed in the president’s controlling parentheses of a math expression. To create a single element tuple, we make use of the trailing comma separator, which we’re allowed to use when specifying literal tuples, lists, and dictionaries.

A single element with a trailing comma is passed as a single element tuple. This leaves us with the problem of how to specify an empty tuple. In actuality the answer is simple.
We just use empty parentheses. here is the demo:

ex2

In many cases, the parentheses of literal tuples may be omitted. This feature is often used when returning multiple values from a function.

Here we make a function to return the minimum and maximum values of a series, the hard work being done by the two built-in functions min and max. Returning multiple values as tuple is often used in conjunction with a wonderful feature of Python called tuple unpacking.Tuple unpacking is a destructuring operation, which allows us to unpack data structures into named references. For example, we can assign the result of our minmax function to two new references like this.

ex3

Tuple unpacking works with arbitrarily nested tuples, although not with other data structures. Should you need to create a tuple from an existing collection object such as a list, you can use the tuple constructor, here also shown for strings.

ex4

Hope you have enjoyed the post. Please share your comments

Advertisements

List in python

Python lists such as those returned by the string’s split method are sequences of objects. Unlike strings, lists are mutable in so far as the elements within them can be replaced or removed, and new elements can be inserted or appended.
Literal lists are delimited by square brackets, and the items within the list separated by commas. Here is a list of three numbers and a list of three strings. We can retrieve elements by using square brackets with a zero-based index, and we can replace elements by assigning to a specific element. See how lists can be heterogeneous with respect to the types of the objects. We now have a list containing a string, an integer, and another string.

ex1

It’s often useful to create an empty list, which we can do using empty square brackets. We can modify the list in other ways.Let’s add some floats to the end of the list using the append method.

ex2

See also how we’re allowed to use an additional comma after the last element, an important maintainability feature.

ex3

Slicing is a form of extended indexing which allows us to refer to portions of a list.To use it, we pass the start and stop indices of a half-open range separated by a colon as the square brackets index argument.

Here we slice three words from the list by passing the start index 1 and the stop index 4. This facility can be combined with negative indexing. For example, to take all the elements except the first and last, slice between 1 and -1. Both the start and stop indices are optional. To slice all elements from the second to the end of the list, supply only 2: as the argument to the index operator.

ex4

we can copy one list object to another list object in the following ways:

ex6

You must be aware, that all of these techniques perform a shallow copy. That is, they create a new list containing the same object references as the source list, but don’t copy the referred to objects.

List repetition:

As for strings and tuples, lists support repetition using the multiplication operator. It’s simple enough to use. Here we repeat a list containing the integers 21 and 37 four times

ex7

To find an element in a list, use the index method passing the object you’re searching for. The elements are compared for equivalence or value equality until the one you’re looking for is found and its index returned. Here we create a list W containing few words , Searching for fox using the index method returns the integer 3, which of course allows us to get ahold of that element. If you search for a value that isn’t present like unicorn, you will receive a ValueError. Another means of searching is to count matching elements using the count method. Here we count occurrences of the word the. If you just want to test for membership, you can use the in operator or for nonmembership using the not in operator.

ex8

Elements from a list can be removed using del or remove as shown below.

ex9

 Before we move on from lists, let’s look at two operations which rearrange the elements in place, reversing and sorting. A list can be reversed in place simply by calling its reverse() method. Similarly, a list can be sorted in place using the sort() method. The sort() method accepts two optional arguments, key and reverse. The latter is self-explanatory, and when set to true gives a descending sort

 
ex10
 
Hope you have enjoyed the post.Please share your comments

 

Format Strings in Python

We have very powerful method str.format() in python through which you can do variable substitutions and value formatting.
Let’s understand the usage of format with couple of examples.

 
ex1

Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format(). The value we want to put into the placeholders and concatenate with the string passed as parameters into the format function.

format() method takes any number of parameters. But, is divided into two types of parameters:
Positional parameters – list of parameters that can be accessed with index of parameter inside curly braces {index} ,See the example below.

ex2

Keyword parameters – list of parameters of type key=value, that can be accessed with key of parameter inside curly braces {key}
See the example :
ex3

we have another method of formatting string literals , as shown below:

ex6

You could also call functions as shown below:

ex7

Hope you have enjoyed the post,please share your comments

Python in SQL Server

Python is an interpreted programming language. Python is a very strong programming language for multi purposes like machine learning/complex computing/ scientific and theoretical based solutions etc. I do not want to cover the details as We have a “Stairway to Python” initiative by Kiran Reddy. I strongly recommend to read the series to know and learn more about Python. For now, Let us cover Python in SQL Server…

Prerequisites

Python support in SQL Server, is a great move from Microsoft to challenge other technologies.SQL Server 2017 by default has in-built Python libraries to support the requirements.

Let us quickly see the prerequisites for Python in SQL Server.

1. Install SQL Server 2017 Developer or above edition

As SQL Server 2017 has introduced support of Python script/code execution, Lets us download and install SQL Server 2017 Developer version as a first step.

2. Select the Machine learning features that includes Python and R while installing SQL Server 2017

It is important for us to understand we need to select Machine Learning Services(previously known as R Services(SQL 2016) in “Feature Selection” while installing SQL Server 2017.

3. Make sure the Launchpad Service is selected with Automatic start-up

Launchpad is an integral part of Machine Learning Services execution meaning to executing the Python or R code in SQL Server. The below diagram explains the usage of Launchpad service.

Note, This is important when you have multiple Launchpad services exists in the same environment and one of them have any issues that could not start, none of the Launchpad services may not start at all(manually). To be safer side, we can make this setting Automatic at initial stage.

4. Enable “External Scripts Enabled” in the configuration

To run Python code in SQL Server, we need to use sp_execute_external_script system stored procedure. To use this procedure, we need to enable the configuration option “external scripts enabled” as below.

sp_configure 'external scripts enabled',1
reconfigure with override

5. Restart the SQL Service

This is important as “External Scripts Enabled” option is not a dynamic configuration that needs an explicit restart of the service to affect the changes.

A quick Demo

Now, we have set up the environment Lets quickly do a script execution.


EXEC sp_execute_external_script @language = N'Python', 
@script = N'print("Python in SQL Server is a revolution!!!")'

Thats it for now, hope you enjoyed the post.

Working with Strings in Python

Strings in Python are identified as a continuous set of characters represented in the quotation marks.We can access subset of strings using Index [] operator.

Slicing methods:

str = ‘SQLZealots’
print(‘str = ‘, str)

#first character
print(‘str[0] = ‘, str[0])

#last character
print(‘str[-1] = ‘, str[-1])

#slicing 2nd to 5th character
print(‘str[1:5] = ‘, str[1:5])

#slicing 6th to 2nd last character
print(‘str[5:-2] = ‘, str[5:-2])

we have many built in methods with strings. I have listed couple of them and have shown the o/p of each method with an example.

string.upper()           # get all-letters in uppercase
string.lower()           # get all-letters in lowercase
string.capitalize()    # capitalize the first letter
string.title()              # capitalize the first letter of words
string.swapcase()    # converts uppercase and lowercase
string.strip()            # remove all white spaces
string.lstrip()           # removes white space from left
string.rstrip()          # removes white space from right
string.split()             # splitting words
string.split(‘,’)          # split words by comma
string.count(‘l’)       # count how many times l is in the string
string.find(‘Wo’)      # find the word Wo in the string
string.index(“Wo”)  # find the letters Wo in the string
“:”.join(string)          # add a : between every char
” “.join(string)          # add a white space between every char
len(string)                # find the length of the string

Strings

Lets write a  small program ,to  extract the Numbers only from a given string .

Code for Extract numbers

You can find the SQL version of the code from here.

Hope you enjoyed the post. Please share your comments .

See also

Introduction to Python

First Program with Python

SQL Server Configuration Manager – The remote procedure call failed. [0x800706be]

Problem Statement:

Recently, I encountered an issue as below with SQL Server Configuration Manager which is a very common issue for most of us. Most of the time, this type of error is related to not having enough permission to see the SQL Server Configuration Manager. However, the case was different for me as I am the administrator for my system.

Observations:

In my laptop, I have multiple SQL versions like 2008 R2, 2014, 2016 and 2017.For some reason, SQL Server Configuration Manager (by default it was pointing to oldest one, nothing but 2008 R2 version) was not able to correctly get the information for all the installed versions. This was causing an issue.

To resolve the issue,

1. we can identify the file location as “C:\windows\syswow64\” OR “C:\Windows\System32\”.
The SQL Server Configuration manager file name should be similar to SQLServerManager**.msc where ** denotes the version of the SQL Server.

2. Open the latest version of SQL Server configuration manager file. This will work as expected.

However, the above is not a complete solution while we open the configuration manager from the start window. This is because, the default configuration manager will still be pointing to the older version of the SQL Server. To change this behavior, we need to do the following steps.

1. Open the “SQL Server Configuration” in start and right click on the icon.


2. Right Click on “SQL Server Configuration Manager” and change the Target file to the latest mmc file.(You should have administrator privilege to do so)


3. Close the Window

From then, you will be successfully able to see the SQL Server Configuration manager that fetch the data as expected.