Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Python Tuples

Tuples are immutable ordered sequences in Python. They are created using parentheses and elements within a tuple are separated by commas. Tuples can contain heterogeneous data types and support operations like indexing, slicing, concatenation and repetition. Though tuples are immutable, their elements can be modified if they contain mutable objects like lists.

Uploaded by

Django x
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Tuples

Tuples are immutable ordered sequences in Python. They are created using parentheses and elements within a tuple are separated by commas. Tuples can contain heterogeneous data types and support operations like indexing, slicing, concatenation and repetition. Though tuples are immutable, their elements can be modified if they contain mutable objects like lists.

Uploaded by

Django x
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

TUPLES

Features of Python Tuple :

Tuples are an immutable data type, meaning their elements cannot be changed after they are generated. Each
element in a tuple has a specific order that will never change because tuples are ordered sequences.

Forming a Tuple:

All the objects-also known as "elements"-must be separated by a comma, enclosed in parenthesis ( ). Although
parentheses are not required, they are recommended.

Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be contained in a
tuple. A comma must separate the element to be recognized as a tuple.

t=3 # int var


t = ( 3, ) # tuple

# Python program to show how to create a tuple having a single element

single_tuple = ("Tuple")

print( type(single_tuple) )

# Creating a tuple that has only one element

single_tuple = ("Tuple",)

print( type(single_tuple) )

# Creating tuple without parentheses

single_tuple = "Tuple",

print( type(single_tuple) )

Accessing Tuple Elements

A tuple's objects can be accessed in a variety of ways.

Indexing
Indexing We can use the index operator [ ] to access an object in a tuple, where the index starts at 0.

The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised assuming we attempt to get
to a list from the Tuple that is outside the scope of the tuple record. An index above four will be out of range in this

B Sampath Kumar 9361835327 Page 1


scenario. Because the index in Python must be an integer, we cannot provide an index of a floating data type or any
other type. If we provide a floating index, the result will be TypeError. The method by which elements can be accessed
through nested tuples can be seen in the example below.

Code

# Python program to show how to access tuple elements

# Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Collection")

print(tuple_[0])

print(tuple_[1])

# trying to access element index more than the length of a tuple . This will result in an error.

print(tuple_[5]) # length of the tuple is only 4 ( 0 – 3 )

# Creating a nested tuple

nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))

# Accessing the index of a nested tuple

print(nested_tuple[0][3])

print(nested_tuple[1][1])

Negative Indexing

Python's sequence objects support negative indexing. The last thing of the assortment is addressed by - 1, the second
last thing by - 2, etc.

Slicing
Tuple slicing is a common practice in Python and the most common way for programmers to deal with practical issues.
Look at a tuple in Python. Slice a tuple to access a variety of its elements. Using the colon as a straightforward slicing
operator (:) is one strategy. To gain access to various tuple elements, we can use the slicing operator colon : .

Deleting a Tuple

A tuple's parts can't be modified, as was recently said. We are unable to eliminate or remove tuple components as a
result. However, the keyword del can completely delete a tuple.

Code

# Python program to show how to delete elements of a Python tuple

# Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")

# Deleting a particular element of the tuple will result in error

del tuple_[3] # Error Item deletion NOT supported.

print(tuple_)

# Deleting the variable from the global space of the program

del tuple_ # Delete the entire Tuple.

B Sampath Kumar 9361835327 Page 2


Iterating Through a Tuple

A for loop can be used to iterate through each tuple element.

Code

# Python program to show how to iterate over tuple elements

# Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Immutable")

# Iterating over tuple elements using a for loop

for item in tuple_:

print(item)

Merging two tuples :

The + operator can be used to combine multiple tuples into one. This phenomenon is known as concatenation.

We can also repeat the elements of a tuple a predetermined number of times by using the * operator.

The aftereffects of the tasks + and * are new tuples. ( ie., a new tuple is created )

Advantages of Tuple over List in Python

Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain
advantages of implementing a tuple over a list:

 We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data
types.
 Since tuples are immutable, iterating through a tuple is faster than with a list. So there is a slight performance
boost.
 Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.

Append elements in Tuple

Tuple is immutable, although you can use the + operator to concatenate several tuples. The old object is still present
at this point, and a new object is created.

Example

Following is an example to append the tuple −

s=(2,5,8)

s_append = s + (8, 16, 67)

print(s_append)

print(s)

Output

Following is an output of the above code −

(2, 5, 8, 8, 16, 67)

(2, 5, 8)

Note− Concatenation is only possible with tuples. It can't be concatenated to other kinds, such lists.

B Sampath Kumar 9361835327 Page 3


Following is an example of concatenating a tuple with a list −

s=(2,5,8)

s_append = (s + [8, 16, 67])

print(s_append)

print(s)

Output

The following error came as an output of the above code −

Traceback (most recent call last):

File "main.py", line 2, in <module>

s_append = (s + [8, 16, 67])

TypeError: can only concatenate tuple (not "list") to tuple

Concatenating Tuple with one element

You can concatenate a tuple with one element if you want to add an item to it.

Example

Following is an example to concatenate a tuple with one element −

s=(2,5,8)

s_append_one = s + (4,)

print(s_append_one)

Output

Following is an output of the above code.

(2, 5, 8, 4)

Note − The end of a tuple with only one element must contain a comma as seen in the above example.

# A program to append new elements to a tuple , getting the values from the keyboard.

t = tuple()

for i in range(5) :

e = int ( input("Number : " ))

t = t + ( e, ) # appending new elements to a tuple. See the comma at the end.

print ( t )

big = max(t)

print("maximum in tuple is = " , big)

Append to a Python Tuple with Tuple Unpacking

You’ll learn another method to append a value to a Python tuple. Specifically, you’ll learn tuple unpacking (using the *
) operator, to append a value to a tuple. Similar to the methods described above, you’ll actually be creating a new
tuple, but without needing to first create a list.

B Sampath Kumar 9361835327 Page 4


The unpacking operator, *, is used to access all the items in a container object, such as a tuple. In order to append a
value, we first unpack all the values of the first tuple, and then include the new value or values.

# Appending to a tuple with tuple unpacking

a_tuple = (1, 2, 3)

a_tuple = (*a_tuple,18)

print(a_tuple)

# Returns: (1, 2, 3, 18)

Let’s break down what we did here:

1) We created our first, original tuple


2) We then generated a new tuple with the same name. In this tuple we unpacked all the values in the original
tuple and then included the new value.

Modify a Tuple’s Contents by Appending a Value

There is one fringe exception where you can append to a tuple without raising an error. Specifically, if one of your
tuples’ items is a mutable object, such as a list, you can modify the item. Really, we’re not appending to the tuple itself,
but to a list contained in the tuple.

Let’s see how we can do this:

# Appending to an item in a tuple

a_tuple = (1, 2, [1, 2, 3])

a_tuple[2].append(27)

print(a_tuple)

# Returns: (1, 2, [1, 2, 3, 27])

Let’s break down what we did here:

1) We created our new tuple, where one item is a list


2) We used the .append() method on our tuples’ list
3) The reason that this works is because we’re not modifying the tuple’s identity but just the object within it.

You can insert new elements to a tuple or do any modification by this method. This is suitable for tuples, sets.

t = ( 1, 2, 3 )

ls = list( t ) # convert the tuple to a list

ls.append(19) # append the element to the list

t = tuple(ls) # convert the list to a tuple with the same name

print( t )

output will be : ( 1, 2, 3, 19 )

The methods find() and count() of the list can also be used as the methods of the tuple to find an occurrence of an
element and to count the frequency of an element respectively.

~~~~~  ~~~~~

B Sampath Kumar 9361835327 Page 5

You might also like