Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

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

Data StructuresAlgorithmsPython Programming

An overview of Python tuples, including their definition, items, comparison with lists, and built-in functions. Tuples are ordered, unchangeable collections of data that can store multiple items in a single variable. They are written with parentheses and allow duplicate values. the syntax of tuples, their advantages over lists, and various tuple operations and built-in functions.

What you will learn

  • What are some common use cases for tuples in Python?
  • What are some built-in functions for manipulating tuples in Python?
  • How are tuples created in Python?
  • What is a tuple in Python?
  • What are the differences between tuples and lists in Python?

Typology: Assignments

2021/2022

Uploaded on 12/14/2022

abdullah-niazi
abdullah-niazi 🇵🇰

3 documents

1 / 18

Toggle sidebar

Related documents


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 .1 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-2020 BSSE (2020A) session 2020-2024 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  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 or 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__())  Different Use Cases At first sight, it might seem that lists can always replace tuples. But tuples are extremely useful data structures 1. Using a tuple instead of a list can give the programmer and the interpreter a hint that the data should not be changed. 2. Tuples are commonly used as the equivalent of a dictionary without keys to store data. Example: [('Swordfish', 'Dominic Sena', 2001), ('Snowden', ' Oliver Stone', 2016), ('Taxi Driver', 'Martin Scorsese', 1976)] Above example contains tuples inside list which has a list of movies. 3. Reading data is simpler when tuples are stored inside a list. Example : [(2,4), (5,7), (3,8), (5,9)] is easier to read than [[2,4], [5,7], [3,8], [5,9]] Tuple can also be used as key in dictionary due to their hash able and immutable nature whereas Lists are not used as key in a dictionary because list can’t handle __hash__() and have mutable nature. .  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 3. The list is better for performing operations, such as insertion and deletion Tuple data type is appropriate for accessing the elements 4. Lists consume more memory Tuple consume less memory as compared to the list 5. Lists have several built-in methods. Tuple does no have must built-in methods. 6. The unexpected changes and errors are more likely to occur In tuple, it is hard to take place. 7. There are 46 available methods on lists. There are 33 available methods on tuples . To get around this, we add a comma after the item. >>> a=(1,) >>> type(a) <class ‘tuple’> Problem solved. And as we saw in tuple packing, we can skip the parentheses here. >>> a=1, >>> type(a) <class ‘tuple’> 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 operation Description example Creating tuples Creating tuples with element of different data types >>>a=(20,40,60, “apple”,”ball”) Indexing Accessing the item in the position 0. Accessing the item in the position 2. >>>print(a[0]) 20 >>>a[2] 60 Slicing Displaying items from 1st till 2nd. >>>print(a[1:3]) (40,60) Concatenation Adding tuples elements at the end of the another tuples elements >>>b=(2,4) >>>print(a+b) >>>(20,40,60,”apple”,”ball”,2,4) Repetition Repeating the tuples in “n” no of times >>>print(b*2) >>>(2,4,2,4) Membership Returns true if the element is present in tuple. Otherwise Returns false. >>>a=(2,3,4,5,6,7,8,9,10) >>>5 in a True >>>100 In a False >>>2 in a False Comparison Returns true if all elements in both elements are same . Otherwise returns false >>>a=(2,3,4,5,6,7,8,9,10) >>>b=(2,3,4) >>>a==b False >>>a!=b True Python tuple built in functions : There are eight python tuple built in function which are given bellow, max((‘Hi’,9)) TypeError: ‘>’ not supported between instances of ‘int’ and ‘str’ c. min() Like the max() function, the min() returns the item with the lowest values. Example : min(a) 1 As you can see, 1 is the smallest item in this Python tuple. d. sum() This function returns the arithmetic sum of all the items in the tuple. Example : sum(a) 21 However, you can’t apply this function on a tuple with strings. sum(('1','2','3')) Traceback (most recent call last): File “<pyshell#57>”, line 1, in <module> 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?
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved