Tuples in Python

Tuple

Tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses whereas lists use square brackets.

Creating atuple is as simple as puttingdifferent comma-separated values. Optionally, you can put these comma-separated values between parentheses. For eg,

tup1 = (‘physics’, ‘chemistry’, 1997, 2000)

tup2 = (1, 2, 3, 4, 5)

tup3 = “a”, “b”, “c”, “d”

The empty tuple is written as two parentheses containing nothing. tup1 = ();

To create a tuple containing a single value, we have to include a comma even though there is only one value.

tup1 = (50,)

Like string indices, tuple indices start at 0 and they can be sliced and concatenated

Accessing values in Tuples:

tup1 = (‘physics’, ‘chemistry’, 1997, 2000)

tup2 = (1, 2, 3, 4, 5, 6, 7 )

print (“tup1[0]: “, tup1[0])

print (“tup2[1:5]: “, tup2[1:5])

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain the value available at that index. For eg,

When the above code is executed, it produces the following result, tup1[0] : physics

tup2[1:5] : [2, 3, 4, 5]

Tuple Assignment :

>>> a, b = 3, 4

>>> print a 3

>>> print b 4

>>> a, b, c = (1,2,3), 5, 6

>>> print a (1, 2, 3)

>>> print b 5

>>> print c 6

Once in a while, it is useful to perform multiple assignments in a single statement and this can be done with tuple assignment:

>>> a, b, c, d = 1, 2, 3

ValueError: need more than 3 values to unpack

The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.

The number of variables on the left and the number of values on the right have to be the same:

Such statements can be useful shorthand for multiple assignment statements, but care should be taken that it does not make the code more difficult to read.

One example of tuple assignment that improves readability is when we want to swap the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b:

temp = a a = b

b = temp

If we have to do this often, such an approach becomes cumbersome. Python provides a form of tuple assignment that solves this problem neatly:

Tuples as return values :

def swap(x, y):

return y, x

Functions can return tuples as return values. For example, we could write a function that swaps two parameters:

Then we can assign the return value to a tuple with two variables:

a, b = swap(a, b)

def swap(x, y):

x, y = y, x

In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to encapsulate swap, which is the following tempting mistake:

If we call swap like this swap(a, b)

then a and x are aliases for the same value. Changing x inside swap makes x refer to a different value, but it has no effect on a in main. Similarly, changing y has no effect on b. This function runs without producing an error message, but it doesn’t do what we intended. This is an example of a semantic error.

Basic tuples operations, Concatenation, Repetition, in Operator, Iteration :

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.

In fact, tuples respond to all of the general sequence operations we used on strings in the previous chapter.

Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
(‘Hi!’,) * 4 (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) Repetition
3 in (1, 2, 3) True Membership
for x in (1,2,3) : print (x, end=’ ‘) 1 2 3 Iteration

Built-in Tuple Functions :

SN Function with Description
1 cmp(tuple1, tuple2)   No longer available in Python 3.
2 len(tuple)   Gives the total length of the tuple.
3 max(tuple)   Returns item from the tuple with max value.
4 min(tuple)   Returns item from the tuple with min value.
5 tuple(seq)   Converts a list into tuple.

Python includes the following tuple functions-

Tuplelen()MethodDescription

The len() method returns the number of elements in the tuple.

Syntax

Following is the syntax for len() method- len(tuple)

Parameters

tuple – This is a tuple for which number of elements to be counted.

Return Value

This method returns the number of elements in the tuple.

Example

The following example shows the usage of len() method. tuple1, tuple2 = (123, ‘xyz’, ‘zara’), (456, ‘abc’)

print (“First tuple length : “, len(tuple1)) print (“Second tuple length : “, len(tuple2)) First tuple length : 3 Second tuple length : 2

When we run above program, it produces following result-

Tuple max() Method

Description

The max() method returns the elements from the tuple with maximum value.

Syntax

Following is the syntax for max() method- max(tuple)

Parameters

tuple – This is a tuple from which max valued element to be returned.

Return Value

This method returns the elements from the tuple with maximum value.

Example

tuple1, tuple2 = (‘maths’, ‘che’, ‘phy’, ‘bio’), (456, 700, 200) print (“Max value element : “, max(tuple1))

print (“Max value element : “, max(tuple2))

The following example shows the usage of max() method. Max value element : phy Max value element : 700

Tuple min() Method

Description

The min() method returns the elements from the tuple with minimum value.

Syntax

Following is the syntax for min() method- min(tuple)

Parameters

tuple – This is a tuple from which min valued element is to be returned.

Return Value

This method returns the elements from the tuple with minimum value.

Example

tuple1, tuple2 = (‘maths’, ‘che’, ‘phy’, ‘bio’), (456, 700, 200) print (“min value element : “, min(tuple1))

print (“min value element : “, min(tuple2))

The following example shows the usage of min() method.

When we run the above program, it produces the following result- min value element : bio min value element : 200

Tuple tuple() Method Description

The tuple() method converts a list of items into tuples.

Syntax

Following is the syntax for tuple() method- tuple( seq )

Parameters

seq – This is a tuple to be converted into tuple.

Return Value

This method returns the tuple.

Example

The following example shows the usage of tuple() method. list1= [‘maths’, ‘chemistry’, ‘phy’, ‘bio’] tuple1=tuple(list1) print (“tuple elements : “, tuple1)

tuple elements : (‘maths’, ‘chemistry’, ‘phy’,’bio’)

When we run the above program, it produces the following result

Please follow and like us:
0

Dotnet courses New features in C# 6.0. Best Dot Net Training

Dotnet courses New features in C# 6.0. Best Dot Net Training

Agenda: New Features of C# 6.0

Dotnet courses New features in C# 6.0. Best Dot Net Training

  1. String Interpolation
  2. Null Conditional Operator
  3. Auto Property Initializer
  4. Dictionary / Index Initializer
  5. Expression-bodied function members
  6. Static Using
  7. name of Expression
  8. Exception Filters
  9. Declaration Expressions
  10. await in catch and finally block

Continue reading “Dotnet courses New features in C# 6.0. Best Dot Net Training”

Please follow and like us:
0

Understanding and Programming Classes and Objects

Understanding and Programming Classes and Objects

In MS.NET when an object is created there is no way to get the address of an object. Only the reference to the object is given through which we can access the members of the class for a given object. When an object is created all the variables (value/ reference types) are allocated the memory in a heap as a single unit and default values are set to them based on their data types.

Account Example:
Steps to create an Account Application:
1. Create a new project (File => New Project). Name: Account Application, Project Type: C#, Template: Windows Application
2. View =>Solution Explorer, Right Click on Project => Add => Class and name it as Account
3. To class, add the following code:
Continue reading “Understanding and Programming Classes and Objects”

Please follow and like us:
0

Working with Assemblies in C# – Bestdotnettraining

Working with Assemblies in C# – Bestdotnettraining Introduction:

    This article explains the Libraries in .NET, Types of DLL, and Assemblies in .NET and its structure, Namespaces and Internal Access Specifier.

Description:
I. Introduction to Libraries
Dynamic Linking Library: A DLL is an application which can have everything that an EXE can have. The difference between them is, an EXE can execute independently but DLL cannot. The code in the DLL can be reused in many other applications but the code in EXE cannot be reused.

II. Types of DLL in Windows OS:
1. Win32 DLL: Here the code is available in the form of simple “C” functions.
2. COM DLL: This DLL has code in the form of reusable COM Components. These are also referred to as ActiveX DLL
3. .NET DLL: These DLL’s (Portable Executables) are used for distributing the reusable classes to various types of .NET applications.

Note:

• The Portable Executable (PE) format is a file format for executables, object code, DLLs, FON Font files and others used in 32-bit and 64-bit versions of Windows operating systems
• PE is a modified version of the Unix COFF file format. PE/COFF is an alternative term in Windows development.
• Microsoft’s .NET Framework has extended the PE format with features which support the Common Language Runtime (CLR).
• The CLR section of it contains two important segments: Metadata and Intermediate Language (IL) code

III. What is Assembly in .NET
An assembly is a collection of types (classes, interface, struct etc…) and resources (bmp, jpg, string table, txt, ico) that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

Assemblies are a fundamental part of programming with the .NET Framework.
• It contains code that the common language runtime executes.
• It forms a security boundary.
• It forms a type of boundary.
• It forms a reference scope boundary.
• It forms a version boundary.
• It forms a deployment unit.
• It is the unit at which side-by-side execution is supported.

Note: We should create a multifile assembly when you want to combine modules written in different languages and to optimize downloading an application by putting seldom-used types in a module that is downloaded only when needed
Note The files that make up a multifile assembly are not physically linked by the file system. Rather, they are linked through the assembly manifest and the common language runtime manages them as a unit.

Assembly Manifest Content:
1. Assembly Name
2. Version Number
3. Culture
4. Strong name information
5. List of all files in an assembly
6. Type reference information of types exported from the assembly
7. Information about other referenced assemblies

IV. About Namespaces
• A namespace is a logical collection of classes and other types with unique names. In a given namespace all the types have a unique name and thus it is used to resolve the ambiguity in case of a name conflict.
• Any type when used outside the namespace, it must be qualified by its namespace, but when used by another type within the same namespace it need not be qualified by the namespace.
• We can use using Namespace on top of the file so that we don’t have to qualify all the types of that namespace in that file explicitly.

V. Internal Access Specifier
• A public Class is accessible within and outside the assembly. Whereas an internal class can be accessed only by other types within the same assembly (irrespective of the namespace of other classes within the assembly).
• Internal is the default access specifier for the class.
• The top-level class can only be declared as either public or internal but nested class (a class within class) can have any access modifier.
• The namespace can never be used as a boundary for an access specifier. It’s used only as a name qualifier.
• An internal member of a class is accessible to all other types within the same assembly and is not accessible outside the assembly.
• A member declared as “protected internal” is accessible to all the class within the assembly and only to the derived classes outside the assembly.
• A public method of a public class cannot have either as a parameter or return type any data type of the same assembly which is not public (or is internal).

VI. Types of Assemblies:
1. Private Assemblies: An assembly whose local copy is maintained by each & every application referencing to it.
2. Shared Assembly: An assembly whose single copy deployed in Global Assembly Cache (GAC) and used/shared by many applications running on that machine. Such assemblies must have a Strong name.
3. Satellite Assembly: A resource-only assembly for a given culture is called as a satellite assembly. They don’t have any code but they have only resources like string tables and images.
4. Dynamic Assemblies: These run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. The API method Reflection. Emit is used to create dynamic assemblies

 

Working with Assemblies in C#
Working with Assemblies in C#

 

Please follow and like us:
0