0% found this document useful (0 votes)
150 views

Tuple & Sort

A tuple in Python is similar to a list but is immutable once created. Tuples use parentheses while lists use square brackets. Tuples can be created by placing comma-separated values within or without parentheses. Individual elements can be accessed using indexes but not updated since tuples are immutable. New tuples can be created by concatenating or adding existing tuples.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
150 views

Tuple & Sort

A tuple in Python is similar to a list but is immutable once created. Tuples use parentheses while lists use square brackets. Tuples can be created by placing comma-separated values within or without parentheses. Individual elements can be accessed using indexes but not updated since tuples are immutable. New tuples can be created by concatenating or adding existing tuples.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Tuple

Introduction
A tuple in Python is much like a list except that it is immutable
(unchangeable) once created.ie the values that you give it first,
are the values that you are stuck with for the rest of the program
and tuples use parentheses and lists use square brackets.
Example:
List1 = [1, 'a', [6, 3.14]] is a list.
Tuple1 = (1, 'a', [6, 3.14]) is a tuple.

Creating Tuples
Creating a tuple is as simple as putting different comma-
separated values and optionally you can put these comma-
separated values between parentheses also.
For example:
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 write a tuple containing a single value you have to include a


comma, even though there is only one value:
tup1 = (50,);

Accessing values in Tuple


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

Example:1
#!/usr/bin/python

tup1 = ('physics', 'chemistry', 1997, 2000);


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

print "tup1[0]: ", tup1[0] # prints first value of tuple


print "tup2[1:5]: ", tup2[1:5] # prints (end-start) values
including end value

This will produce following result:


tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Example:2
#!/usr/bin/python
months = ('January','February','March','April','May','June',
'July','August','September','October','November','December')

 Technically you don't have to put those parentheses ( ) but it


stops python from getting things confused.
 You may have spaces after the commas if you feel it necessary
- it doesn't really matter.
Python then organizes those values in a handy, numbered index -
starting from zero (from left) or from -1 (from right), in the order
that you entered them in. It would be organized like this:
months[] Index Value
0 or -12 January
1 or -11 February
2 or -10 March
3 or -9 April
4 or -8 May
5 or -7 June
6 or -6 July
7 or -5 August
8 or -4 September
9 or -3 October
10 or -2 November
11 or -1 December

Updating Tuples
Tuples are immutable which means you cannot update them or
change values of tuple elements. But we able able to take
portions of an existing tuples to create a new tuples as follows:
Example:
#!/usr/bin/python

tup1 = (12, 34.56);


tup2 = ('abc', 'xyz');

#we can add elements to tuple


tup1 = tup1 + (10,)

# It is a way to create tuples


tup3 = tup1 + tup2;
print tup3;

# Another way to create a new tuple as follows


tup1 += tup2;
print tup1

This will produce following result:


(12, 34.56, 'abc', 'xyz')
(12, 34.56, 'abc', 'xyz')

Deleting Tuple Elements


Removing individual tuple elements is not possible. There is, of
course, nothing wrong with putting together another tuple with
the undesired elements discarded.

To explicitly remove an entire tuple, we use the del statement:


Example:
#!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000);

print tup;
del tup;
print "After deleting tup : "
print tup;

This will produce the following result


Before deleting tup :
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined

An exception raised, this is because after del tup tuple does not
exist anymore:
Tuples have no methods
You can't add elements to a tuple. Tuples have no append or

extend method.
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t.append("new")
Traceback (innermost last):
File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'append'

You can't remove elements from a tuple. Tuples have no

remove or pop method.


>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t.remove("z")
Traceback (innermost last):
File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'remove'

You can't find elements in a tuple. Tuples have no index

method.
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t.index("example")
Traceback (innermost last):
File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'index'

You can, however, use in to see if an element exists in the

tuple.
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> "z" in t
1

Conversions
Convert list to tuples using the built in tuple() method.
>>> l = [4, 5, 6]
>>> tuple(l)
(4, 5, 6)

Converting a tuple into a list using the built in list() method to


cast as a list:
>>> t = (4, 5, 6)
>>> list(t)
[4, 5, 6]

Basic Tuples Operations:


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.

Python Expression Result Description


Len((1, 2, 3)) 3 Tuple 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, 1 2 3 Iteration

Sorting Tuple
The following program shows you how to sort a tuple.

tuple1=() # Create an empty tuple

n = int (raw_input("Enter an Integer for the length of Tuple:


")); # assign the length of the tuple given by user to n

# asks user for elements of tuple


for i in range(n):
print "\nIf you want to enter a string, type the string in
Single Quotes(Ex: 'bbc')"
x = input("Enter Values of tuple : ");
tupElement = x
tuple1 = tuple1 + (tupElement,)
print "\nTuple you have entered is: ", tuple1 # Tuple entered
by the user

ls = list(tuple1) # convert tuple to list

def sortTuple(lst): # function to sort a list


for i in range(len(lst)-1):
for j in range(len(lst)-1):
if lst[j]>lst[j+1]:
t = lst[j]
lst[j]=lst[j+1]
lst[j+1]=t
return lst

sortTuple(ls) # call sort function


tup1 = tuple(ls) # convert list back to tuple
print tuple1 # prints sorted tuple

As we cannot change the tuple values, we use list(tuple),


tuple(list) to convert tuple to list and list to tuple respectively.
After converting the tuple to list we sort it and again convert the
list back to tuple.

Exercise Problems:

1. Define ‘tuple’ and differentiate ‘tuple’ and ‘list’ with


examples.
2. Find the length of a tuple without using in-built function
“len(tuple)”.
3. Create a tuple of strings and then sort the tuple in
alphabetical order.

You might also like