Docsity

Python Tuples: Definition, Items, Comparison with Lists, and Built-in Functions, Assignments of Programming Methodologies

Partial preview of the text

Download Python Tuples: Definition, Items, Comparison with Lists, and Built-in Functions and more Assignments Programming Methodologies in PDF only on Docsity!

Assignment No.

On

What is tuple? comparison with list, how tuples are created? basic tuple operations, built-in functions used in tuples, and examples.

Submitted By: ABDULLAH CU-1230-

BSSE (2020A)

session 2020-

Submitted To : Dr. Kifayat Ullah Assistant Professor Computer Science

DEPARTMENT OF COMPUTER SCIENCE CECOS University of IT and Emerging Sciences Peshawar 2 January 2021

o Python collection types :

A collection is a single object representing a group of

objects.

Or

Collections in Python are containers that are used to store collections of data .collections module was introduced to improve the functionalities of the built-in collection containers.

These collection types support various types of data

structures and ways to process elements within those structures.

There are four collection data types in the Python. o List o Tuple o Set o Dictionary

What is tuple?

In Python, a tuple is similar to List except that the objects in tuple are immutable which means we cannot change the elements of a tuple once assigned. On the other hand, we can change the elements of a list.

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets

Comparison between tuples and list :

  1. The elements of a list are mutable whereas the elements of a tuple are immutable.
  2. When we do not want to change the data over time, the tuple is a preferred data type whereas when we need to change the data in future, list would be a wise option.
  3. Iterating over the elements of a tuple is faster compared to iterating over a list.
  4. Elements of a tuple are enclosed in parenthesis whereas the elements of list are enclosed in square bracket.

 Syntax Differences

Syntax of list and tuple is slightly different. Lists are surrounded by square brackets [] and Tuples are surrounded by parenthesis ().

Example :

list_num = [1,2,3,4]

tup_num = (1,2,3,4)

print(list_num)

print(tup_num)

Above, we defined a variable called list_num which hold a list of

numbers from 1 to 4.The list is surrounded by brackets []. Also, we

defined a variable tup_num; which contains a tuple of number from 1 to 4. The tuple is surrounded by parenthesis ().

 Mutable List vs Immutable Tuples:

List has mutable nature i.e., list can be changed or modified after its

creation according to needs whereas tuple has immutable nature i.e., tuple can’t be changed o r modified after its creation.

Example:

list_num[2] = 5 print(list_num)

tup_num[2] = 5 In above code we assigned 5 to “ list_num ” at index 2 and we found 5 at index 2 in output. Also, we assigned 5 to “ tup_num ” at index 2 and

we got type error. We can't modify the tuple due to its immutable

nature.

 Size Comparison :

Tuples operation has smaller size than that of list, which makes it a bit faster but not that much to mention about until you have a huge number of elements

Example:

a= (1,2,3,4,5,6,7,8,9,0) b= [1,2,3,4,5,6,7,8,9,0]

print('a=',a.sizeof()) print('b=',b.sizeof())

 Difference Between List and Tuple in Python:

 Key points to remember:

  1. The literal syntax of tuples is shown by parentheses () whereas the literal syntax of lists is shown by square brackets [].
  2. Lists has variable length, tuple has fixed length.
  3. List has mutable nature, tuple has immutable nature.
  4. List has more functionality than the tuple.

s.no LIST TUPLES

  1. Lists are mutable Tuple are immutable
  2. Implication of iterations is Time-consuming

Implication of iterations is comparatively Faster

  1. The list is better for performing operations, such as insertion and deletion

Tuple data type is appropriate for accessing the elements

  1. Lists consume more memory Tuple consume less memory as compared to the list
  2. Lists have several built-in methods.

Tuple does no have must built-in methods.

  1. The unexpected changes and errors are more likely to occur

In tuple, it is hard to take place.

  1. There are 46 available methods on lists.

There are 33 available methods on tuples.

o Advantages of Tuple over List

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. Below listed are some of the main advantages:

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

o How to Create a Python Tuple:

For the creating a python tuple .first we are

To declare a Python tuple, you must type a list of items separated by commas, inside parentheses. Then assign it to a variable.

>>> percentages=(90,95,89)

You should use a tuple when you don’t want to change just an item in future.

a. Python Tuples Packing

To get around this, we add a comma after the item.

>>> a=(1,)

>>> type(a)

Problem solved. And as we saw in tuple packing, we can skip the parentheses here.

>>> a=1,

>>> type(a)

Creating tuple

In this example, we are creating few tuples. We can have tuple of same type of data items as well as mixed type of data items. This example also shows nested tuple (tuples as data items in another tuple).

tuple of strings

my_data = ("hi", "hello", "bye") print(my_data)

tu

ple of int, float, string my_data2 = ( 1 , 2.8, "Hello World") print(my_data2)

tuple of string and list

my_data3 = ("Book", [ 1 , 2 , 3 ]) print(my_data3)

tuples inside another tuple

nested tuple

my_data4 = (( 2 , 3 , 4 ), ( 1 , 2 , "hi")) print(my_data4) Output:

('hi', 'hello', 'bye') ( 1 , 2.8, 'Hello World') ('Book', [ 1 , 2 , 3 ]) (( 2 , 3 , 4 ), ( 1 , 2 , 'hi'))

Empty tuple :

empty tuple

my_data = ()

Tuple with only single element:

Note: When a tuple has only one element, we must put a comma after the element, otherwise Python will not treat it as a tuple.

# a tuple with single data item my_data = ( 99 ,)

Basic tuples operations :

  1. Indexing
  2. Slicing
  3. Concatenation
  4. Repetitions
  5. Membership
  6. Comparison

a. Len()

Like a list, a Python tuple is of a certain length. The len() function returns its length.

Example :

my tuple

(1, 2, 3, [6, 5])

Len(my tuple)

It returned 4, not 5, because the list counts as 1.

b. max()

It returns the item from the tuple with the highest value.

We can’t apply this function on the tuple my tuple, because its cannot be compared to a list. So let’s take yet another tuple in Python.

Example :

a=(3,1,2,5,4,6) max(a)

6

Let’s try that on strings.

max(('Hi','hi','Hello'))

‘hi’

‘hi’ is the greatest out of these, because h has the highest ASCII value among h and H.

But you can’t compare an int and a string.

max(('Hi',9))

Trace back (most recent call last):

**File “”, line 1, in **

sum((‘1′,’2′,’3’))

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

e. any()

If even one item in the tuple has a Boolean value of True, then this function returns True. Otherwise, it returns False.

Example :

any(('','0',''))

True

The string ‘0’ does have a Boolean value of True. If it was rather the integer 0, it would’ve returned False.

any(('',0,''))

False

f. all()

Unlike any(), all() returns True only if all items have a Boolean value of True. Otherwise, it returns False.

Example :

all(('1',1,True,''))

False

g. sorted()

This function returns a sorted version of the tuple. The sorting is in ascending order, and it doesn’t modify the original tuple in Python.

Example :

sorted(a)

[1, 2, 3, 4, 5, 6]

h. tuple()

This function converts another construct into a Python tuple. Let’s look at some of those.

Example :

list1=[1,2,3] tuple(list1)

(1, 2, 3)

string1="string" tuple(string1)

(‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’)

How well would it work with sets?