Python: Tuples and Sets

Tuples

Tuples are a grouping of data in Python similar to a list, except tuples are immutable, meaning you cannot add or delete items from the tuple.

Tuples are created using  () instead of []. A tuple with a single value still requires a comma though. x = (1,)

pythontuple

Notice attempting to delete an element from the tuple results in an error.

Set

Sets are another method of hold data collections, but they have some interesting factors other methods do not. Sets are very useful as they only return unique elements for the data they store.

pythontuple2.jpg

 

Looking at the example below, notice how the second set has 4 elements, but the output is only 3. This is due to the fact that sets only return unique values.

You create a set using set() like above, or you can just use {}

pythontuple1.jpg


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

 

Advertisements

Python: lambda, map(), reduce(), filter()

Lambda()

One of the guiding principles of Python is simplicity. In fact, you will often see well coded, simplistic Python programs called Pythonic as tribute to the programmer’s talent at crafting clean code.

When I think of Pythonic code, the first thing that comes to my mind is lambda

The best way I can describe lambda is as a short cut function. Look at the function in ln[12]. This function accepts 1 argument “y”.  It then multiplies it by 2 and returns the result.

Now look at ln[13]:

syntax:

x               = lambda            y        :    y*2

ASSIGNED VARIABLE = lambda ARGUMENT: ACTION

 

pythonLambda

map()

Let’s build on lambda and introduce a new function: map()

Start with ln[15] :

  • lst = [1,2,3,4] – we assign lst a list of numbers
  • n = 0 – setting a counter variable
  • for i in lst: – start a for loop, iterating through the numbers in lst
  • lst[n] = i * 2 – replace each value in lst with the original value * 2
  • n += 1 – iterates n by 1
  • lst – outputs new values of lst

pythonLambda1.jpg

Now let’s examine ln[16]:

  • lst = [1,2,3,4] – we assign lst a list of numbers
  • x = map(lambda y:y*2, lst) – one at a time, pass each value in lst to the lambda function – multiply these values by 2 and assign the results to x
  • x – outputs results

reduce()

Reduce takes all the elements in a list an combines them.

In the example below, x is fed into the lambda function a * b as such:

1*2=2*3=6*4=24

pythonLambda2

filter()

Filter allows you to run a set of values through a function and filter out the false results.

Below we filter out all values from x that are less than 0

pythonLambda3.jpg

 


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT

Follow this link for more Python content: Python