0% found this document useful (0 votes)
8 views22 pages

5 Unit Python

The document provides an introduction to Python programming with a focus on tuples, including their creation, basic operations, and methods. It explains how to access tuple items through indexing and slicing, as well as the relationship between tuples and other data structures like lists and dictionaries. Additionally, it covers tuple packing and unpacking, along with built-in functions that can be applied to tuples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
8 views22 pages

5 Unit Python

The document provides an introduction to Python programming with a focus on tuples, including their creation, basic operations, and methods. It explains how to access tuple items through indexing and slicing, as well as the relationship between tuples and other data structures like lists and dictionaries. Additionally, it covers tuple packing and unpacking, along with built-in functions that can be applied to tuples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Introduction to Python Programming = (‘cem’, "timbernerslee", "www", 1980) 1 ((cem;,timbemerslee, ‘www’, 1980) 3. >>> typetinternet) , 4. >>> fl="ferrari’,"redbull’, "mercedes", *williams’, "renault 5.>>> fl (ferrari, ‘redbull, ‘mercedes’, ‘williams, renault’) 6. >>> type(fl) In BY, the tuple internet is assigned with a. sequence of numbers and string types. The con- tents of the tuple are displayed by executing the tuple name internet @). The contents and ‘ree ofitemsin the tuple are the same as they were when the tuple was created. In Python, tre tuple type is called tuple S). On output, tuples are always enclosed in parentheses, eg that they are interpreted correctly. Tuples can be constructed with or withont sue rounding Parentheses, although often parentheses are used anyway. Itis actually the comma ther forms.a tuple making the commas significant and not the parentheses @y <2 You-can create an empty tuple without any values. The syntax is, tuple_name = 0 Forexample, 1. >>> empty_tuple=() 2 >>> empty tuple 0 3. >>> type(empty_tuple) Oo cely piece becreatedasshown in land empy tiple of ipletype For example, 4, >>> airforce = (115%, "22a", “5,") 2, >>> fighter jels= (1988, 2005, 2016, air ‘orce) > fighter jets > (2005, 206, (5,22 59) ghter_jets) Tuples and Sets Here air_force is of tuple types along with ‘ype B8. The tuple : Gort ite 4 tuple @. A special oro ms: the syntax has some extra nein i econ Of sequence of integer "adhe construction of tuples contaings accommodate these, For example es 1. >>> empty =() 2, >>> singleton = ‘hello’ 3, >>> singleton Chellos) Empty wr ge We Constructed by an empty pair of parenthe constructed by Re ses 6, A tuple with one item is CaRtructe by having followed by a comma ®, It is not sufficient to enclose a single a Basic Tuple Operations Like in lists, you can use the + of »Perator to concatenate tuples together and the * to repeat a sequence of tuple items, Fe aaa For example >>> tuple ; 2,0,1,9) >>> tuple_1 + tuple 2 2,0,1,4,2,0,1,9) 4. >>> tuple 1*3 (2,0, 1,4,2,0,1,4,2, 0,1,4) 5.>>> tuple 1—= tuple 2 False 1 Two tuples, tuple_1 and tuple_2, consisting of integer type are created BI-@). The ty tuple 2tuples are added to forms Taro Thenee iets allitems ofboth tuples ©. You can use the multiplication operator * on tuples. The items in th repeated the number of times you specify, and in @ the tuple_1 times. In @) the items in tuples are compared using = equ Boolean False since the items in the tuples are You can check for the presence of an item in a tu operators, It returns a Boolean True or False. Fo 1. >>> tuple_items = (1, 9,8 8) 2. >>> 1intuple_items Introduction t0 Python Progr 0.777 Seay {mare used to compare tuples, Fo eres ee mrincn oraratocs Hil @/ 253 and fare used t pare tupl example 977 Oy : : - eis 1, >>> tuple_1=(9, 8,7) we >>> tuple_2=(9, 1, 1) ¥ ee 3 >>> tuple_1> tuple 2 oe True ; ss 4, >>> tuple_1 l= tuple_2 ee ae ; “eS we Tuples are compared position by position. The first item of the fi the first item of the second tuple; if they comparison, or else the second item of the second tuple; f they are not eqi ist tuple is compared to are not equal then this will be the result of the first tuple is compared to the second item of the al then this will be the result of the comparison, else the third item is considered, and soon 1-0) The tuple”) Function ‘Thebuilt-in tuple) function is used to createa tuple The syntax for the tuple() function is, tuple(tsequence)) where th specified, ance can bea number string or tuple itl. If the optional sequence is not hen an empty tuple is created 1. >>> norse 2. >>> string_to_tuple = tuple(norse) 3. >>> string to tuple (v,3, k,n g's) 4. >>> zeus =['g%,"0!, "a", "0! "0% 5. >>> list_to_tuple= tuple(zeus) 6. >>> list to tuple (8,°0' 4,0, fs, &, y) 7. >>> string_to_tuple + "scandinavia® Traceback (most recent call last File"", line 1,in TypeError: can only concatenate tuple (not str) to tuple 8 >>> stzing_to_tuple + tuple('scandinavia") (v, I, 8,8, 9 n'a 9, >>> list to_tuple + ['g', "0", J "vikings" Tuples and Sets 14, >>> nested_tuples ((2,°b, ©), (1, 2,3) 15. >>> tuple(wolverine’) (w, 0}, v ‘¥, i) nye) tne string variable Bl is converted to a tuple using the fuplt) function @, Not only strings, But even list variables @ can be converted ta tuples If you try to commend either a string © ora list @ with tuples, then it results in an error. You have toconeeey strings and aetatg tuples using tuple) function before concatenating with tuple types @ and Nesting of tuples 's allowed in Python. An output of a tuple operation is always enclosed in Parentheses so that nested tuples are interpreted correctly ®, Bach individual charac-ter ‘na string is separated by a comma when a string is converted toa tuple. & —————= Indexing and Slicing in Tuples Each item in a tuple can be called individually through indexing, The expression inside the brackets called the index. Square brackets [] are used by tuples to access individual items, with the first item at index 0, the second item at index 1 and so on. The index pro- vided within the square brackets indicates the value being accessed. The syntax for accessing an item in a tuple is, tuple_namelindex] where index should always be an integer value and indicates the item to be selected. For the tuple holy_places, the index breakdown is shown below. holy places S e ———+ [TersaTent | ashivshnanath* | "iarmandialib™ [beleben® "raped 0 1 2 3 4 For example, 1, >>> holy_places hem’, "mahabodhi") >>> holy_places ‘ i Gertsalon ‘kashivishwanath, ‘harmandirsahib) bethlchem, 3, >>> holy_places{0] ‘jerusalem’ 4. >>> holy_placesf!] ‘kashivishwanath’ ul Introduction to Python Programming >>> holy_places[5] Traceback (most recent call last): File "", line 1, in IndexError: tuple index out of range The first item in the tuples displayed by using square brackets immediately after the tuple name with an index value of zero [Y. The range of index numbers in this tuple is0to4, If the index value is more than the number of items in the tuple @, then it results in dexError: tuple index ge” error. In addition to positive index numbers, you can also access tuy index number, by counting backw. indexing is useful if you have a lar tem Fort ple items using a negative ards from the end of the tuple, starting at 1. Negative 'ge number of items in the tuple and you want to locate wards the end of a tuple. e same tuple holy_places, the negative index breakdown is shown below. holy_nlaces jecalen” [Masham "hatrandirsahib® | "bethlehem” | "mahabodhi™ Gi 4 3 4 + For example, 1. >>> holy_places{-2} ’bethlehem’ Ifyou would like can do so as in specifying an index range along The syntax for tuple slicing is, where both start and stop returns a part of the tup! Tuples and sets 3. >>> colors{1:4) (i, 5g) 4.555 color (8B, 8h 5.>>> colors{3} (8)'Y, 05) 6 >>> colorst] (v7, bye) 7. >>> colorsf:] (0 B)'8) Y, 0} r) 8 >>> colors[152] (rg) 9.>>> colors{:2] (vb, y,) 10. >>> colors[-1] The colors tuple has seven items of string type. All the items in the colors tuple starting from an. index value of 1 up to an index value of 4, bt excluding the index value of is sliced @. If yous want to access the tuple item from start index, then there is no need to specify an index valle of zero. You can skip the siart index value and specify only the stop index value @, Similarly, if you want to access the items in a tuple up to the end of the tuple, then there is no need to specify the stop value and you must mention only the start index value (). If you skip both the start and stop index values ©) and specify only the colon operator within the brackets, then all the items in the tuple are displayed. The use of double colons instead of a single colon also displays the entire contents of the tuple @. The number after the second colon tells Python that. you would like to choose your slicing increment. By default, Python sets this increment to 1, but that number after the second colon allows you to specify what you want it to be @), Using double colon as shown in ©, means no value for start index and no value for stop index and jumps the items by two steps: Every second lea er ata ela from an index value of zero. All the items in a tuple can be displayed in reverse order by specifying double colon followed by an index value of -1 . Negative index values car “ start and stop index values e Introduction to Pytion am TABLE Built-In Functions Used on Tuples Func >> years = (1987, 1985, 1981, 1996) 2, >>> len(years) 4 >>> sum(years) 7949 4. >>> sorted _years = sorted years) 5. >>> sorted_years [1981, 1985, 1987, 1996 You can find the number of items in the tuple years by using the len() function Q, Using the. gum() function results in the adding up ofall the number items in the tuple @. The sorted() fanction retums the sorted list of items li siinout modifying the original tuple which ig on eh ROneW list variable ©. In the case of string iteme ine, tuple, they are sorted based _ on their ASCII values, > ee 7 elation between Tuples and Lists Though tuples may different purpose of elements that a 1. >>> coral_reef= (‘great_barrier' "ningaloo_coast, " 2, >>> coral_reef[0]="pickles reef" Traceback (most recent call last): File"", line, in > german cars [porsche’, “audi 2. >>> european_cars = ("forra an_cars, (ferrari volvo) ‘re then you can change it, Consider the pr any change fo the list get reflected on he oeoranae "bmw" "volvo", "rer naull’, getman_cars) 3. >>> europe, "nault} (porsche, ‘audi, bmw’) ‘uropean_cars[3}.append( mercedes") 5. >>> ge 433s ey man_cars (porsche, ‘audi’ bmw’, mercedes!) 6 >>> european _cars (Cerra ‘olvo; ‘renault; [ porsche, ‘audi, bmw, ‘mercedes']) _ he tuple containing” alist seems to change when the underlying list. changes, The key insight {hat tuples have no way of knowing whether the items inside them are mutable, The only thing that makes an item mutableis tohavea method tha alters its data. In genera, there eno May to detect this. In fact, the tuple did not change. Itcould not change because it does not have! Tiutating methods. When the list changes, the tuple does not get notified of the change. The list does not know whether its referred to by a variable, a tuple, or another list BI) The tuple itselfis not mutable ast does not have any methods that can be used for changing its contents. Likewise, thestring is immutable because strings donot have any mutating methods, Relation between Tuples and Dictionaries Tuples can be used as key-value pairs to build dictionaries. For example, 1. >>> fish_weight_kg 1400)) 2. >>> fish_weight_kg_dict 3, >>> fish_weight_kg dict . {'white_shark’ 520, beluga’: 1571, ‘greenland_shark’ The tuples can be converted to dictionaries by, This is achieved by nesting tuples within tupl have two items init Bl-®) The first item the tuple gets converted toad The meth /hite_shark’, 520), ‘beluga’, 1571), ('greenland_shark’, lict(fish_weight_kg) Introduction t0 Python p 3. >>> for company, year in founding. [Link]() 5 me ai? print(f"{company) was found in the year (year}") is a Ourrer o Google was found in the year 1996 3 Apple was found in the year 1976 gee" Sony was found in the year 1946 ebay was found in the year 1995 IBM was found in the year 1911 The fy loop in @ has two iteration variables—compeny and year, because the items() method es three eof the dictionary’s key and value pairs as tuples, which successively “erates through each ofthe keyoalué pairs in the dictionary. a Tuple Methods You can get a lst of all ‘uple function to dir), —_—_______ | -a ‘hemethods asociated withthe tuple (TABLE 8.2) by passing the 1. >>> dixtupie) Sit, “subclasshook ‘count, index Various methods associated with huple are displayed 6. TABLE 8,2 Vatious Tuple Methods Tuple Methods ‘upl_ name countGiemp ‘tuple_name.index(tem) Tuples and Sets Tuple Packing and Unpacking The statement t = 12345, 54321, ‘hello! is an example of tuple pack of ,acking. 1. >>> t= 12345, 54321, ‘hello! Doost (123. ‘hellot’) ‘The values 12345, 54321 and ‘hello!’ are packed together intoa tuple BIO. The reverse operation of tuple packing is also possible, For example, L>>>xy,zet 2. >>>x 12345 Bos>y 54321 4>>>z “hello!” This operation is called tuple unpacking and works for any sequence on the right-hand side, Tuple unpacking requires that there are as many variables on the left side of the equals sign as there are items in the tuple J-®. Note that multiple assignments are really just a combination of tuple packing and unpacking. Traversing of Tuples ‘You can iterate through each item in tuples using for loop. Program 8.1: Program to Iterate Over Items in Tuples Using for Loop Jectric_eel", "jelly_fish’, "shrimp", "turtles", "blue_whale”) 4, ocean_animal 5, def main(): 6 for each_animal in ocean_animals: 7. print(f'{each_animal) is an ocean animal’) 8 if_name__—="_main_" Populating Tuples with Items Enter an item to add: 3 Introduction t0 Python Dro You can populate tuples with items using += operator and also by converting list tema tuple items. Program 8.2: Program to Populate Tuple with User-Entered Items 10. tuple items 0) ‘Ltotal_items = int(input(’Enter the total number of items: ")) 12 for jin range(total_items) 13._user_input =int(input("Enter a number: ") 14. tuple items += (user_input,) 15, print(f'Ttems added to tuple are (tuple_items}") 16 list_items =|] 1, total_items = int(input("Enter the total number of items: ")) a 18. for iin range(total_items): 19, item = input(’Enter an item to add: ") 20, _list_items.append(item) 21. items_of_tuple = tuple(list_items) 2. print(€*Tuple items are {items_of tuple}") Ourer Enter the total number of items: 4 Enter a number:4 Enter a number: 3 Enter a number: 2 Entera number: 1 Items added to tuple are (4, 3,2, 1) Enter the total number of items: 4 Enter an item to add: 1 Enter an item to add: 2 Tuples and Sets For each iteration ®, the user o the user entere is then converted to tuple sing ap tae nl ‘ye using tpt funetohnele4® lo the ist variable The Write Python Program to Swap 7 te/Temporary Varia ine User lumbers Without bles. Prompt See the User for Input 1. def maing: 2 a= intGinput(’Enter a value for first number )) 3 NM(NPurCEnter a value for second number") 4 ab 5. _print(’After Swapping’) © Print(f'Value for first number (a) 7 _print(f"Value for second number (5)") 8 if _name_ 9%. maing) Ovreur Enter a value for the first number 5 Enter a value for the second number 10 After Swapping Value for first number 10 Value for second number 5 a The contents of variables a and b are reversed @. The tuple variables are on the left side of the assignment operator and, on the right side, are the aaa The aap variables on the left and the number of vahes on the righthas to be the same. is assigned to its respective variable. ities Program 8.4: Program to Demonstrate the Return of Multiple Values from a Funet 1. def return_multiple_items(): 2. monument 8. year = input("When was it constructed? ") 4 return monument, year : Introduction t0 Python Prog Ourrur Which is your favorite monument? Hawa Mahal When was it constructed? 1799 J My favorite monument is Hawa Mahal and it was constructed in 1799 Woich is your favorite monument? Big Ben When was it constructed? 1858 My favorite monument is Big Ben and it was constructed in 1858 The function return_multiple_items() returns multiple values that are actually a tuple ling functions that return a tuple itis common to assign the result to multiple vari This is simply tuple unpacking, The return value could also have been assigned to. variable @ Program 85: Write Python Program to Sort Words in a Sentence in Decr Orser of Their Length. Display the Sorted Words along with Their Length 1. def sort_words(user_input): 2 list_of_words = user_input split() 3. words = list) 4 for each_word in list_of_words: 5. [Link]((len(each_word), each_word)) 6 — [Link](reverseTrue) 7. print("After sorting’) 8 for length, word in words: 9. print(fThe word "{word)' is of {le 10. def main(): 11 sentence = input("Enter a ser 12 sort_words(sentence) 13 if_name_—"_m 14 main() ; Tuples and Sets the length of word items ®, The sort() method compares the tuples. in the list based on the length of the wore That isthe first item in the tuple, The second item in the tuple is c nsidered only when the first items a ‘the same and to break thetie. in the rword argument reverse=T rv tells the aorl() method to sort in decreasingorder list with a number as the first item in the tuple, you © By inserting alist of tuples into the UNS he list of tuples. Word length and the ‘word itself are printed using a for the word and the can easily 8 Joop ®-8 thonie Code to Sort a Sequence of Names according Program 8.6: Write Py Without Using sort() Function to Their Alphabetical Order 1. def read_list_items() 2 print("Enter names separated by 3. _listLitems=input() split) 4, retum list_items space’) 5, def sort_item_list(items_in_list): 6 n=len(items_in_list) 7, foriinrange(n): 8 forjinrange(1,n-i): 9. if items_in_list{j-1] > items_in_listfj}: 10. (items_in_list(j-1), item: 1. _print(“After Sorting”) 12. print(items_in list) items_in_listfj]items_in_ist{-1)) 13, def mainQ: 14, _all_items=read_list_items() 45, sort item_list(all_items) 16, if _name_—="_main_" Tuples and Sets Sets Fython also includes a data type for sets. A set is an unordered collection with no dupli- cate items. Primary uses of sets inchide membership testing and eliminating duplicate entries, Sets also support mathematical operations, such as union, intersection, difference, and symmetric difference, Curly braces (or the set() function can be used to create sets with a comma-separated list of tems inside curly brackets {}. Note: to create an empty set you have to use set() and not {as the latter creates an empty dictionary. 1. >>> basket = apple’ ‘orange’, ‘apple’, ‘pear, ‘orange’, banana’) 2, >>> print(basket) (pear, ‘orange’, banana’, apple} 3. >>> orange’ in basket True 4. >>> ‘crabgrass’ in basket False >>> a=set/abracadabra’) >>> b=set(alacazam') (da by, ) B>>>b {im Tye) %)'a) Sets are mutable, Indexin 8 is not possible in sets, since ct ane >> din(set) (and \_delattr_%, ‘dir! format_’ ‘_hash_’ '_iter_', '_ixor_', 4 _ 5 '_reduce_; <_', ‘_repr_!, = tattr, '_sizeof_','_str_J, ‘_sub_!, ;_suib- elasshook = 'adal, ‘clear ‘copy, difference’ “difference_update’, ‘discard’, ‘int \ ‘intersection_update, ‘isdisjoint, 'issubset’, issuperset, ‘pop, ‘remove, ‘symmetric_difference’, ‘symmetric_difference_update’, ‘union’, ‘update'] Various methods associated with set are displayed TABLE Various Set Methods Set Methods Syntax Description dad) set name ada{iter) ‘The edd) method adds an item to the set ear) set_namesclear() ‘The clear) method removes all he tems fi set name. differenced) set_name difference(‘others) iscard) set name discard(item) intersection) _set_name.intersection("others) Isdisoint)) sel_name isdisjoint(other) issubset() Tuples and Sets For example, sunflowers’, "roses", "lavender", “tulips, "goldcrest’) ‘roses’, "tulips',"lilies’, “daisies") 3. >>> american_flowers.add("orchids") 4, >>> american_flowers.difference(european_flowers) (lilies, ‘orchids, ‘daisies’ 5, >>> american_flowers.intersection(european_flowers) {'roses', tulips!) 6. >>> american_flowers.isdisjoint(european_flowers) False 7, >>> american_flowers.issuperset(european_flowers) False 8, >>> american _flowers.issubset(european_flowers) False 9, >>> american_flowers. symmetric _difference(european_flowers) (lilies, ‘orchids, ‘daisies, ‘goldcrest, ‘sunflowers, lavender 10, >>> american_flowers.union(european_flowers) (lilies, "tulips, ‘orchids, sunflowers, lavender, ‘roses, ‘goldcrest, daisies} U1, >>> american_flowers.update(european_flowers) 12, >>> american_flowers {ities, tulips, ‘orchids, ‘sunflowers, lavender, ‘roses, goldcrest, ‘daisies 13, >>> american_flowersdiscard( "ros 414, >>> american_flowers (lilies, ‘tulips, ‘orchids; ‘daisies') 45, >>> european [Link]() “tulips! 16, >>> american_flowers.clear() 17, >>> american flowers set) Various operations onsets are carried out using set methods Keo Introduction to Python P for each_ship in warships: Print(ffeach ship} is a Worship") if__no main, Warship Warship NS_airavat is a We ins_hetz is a W. arship Here warships is of a set ty Program 8.8: Write a Function Which Receives a Variable Numb Strings as Arguments. Find Unique Characters in Each String | 1. def find_unique(‘all_words): 2 for each_word in all_words: A 5. def main: 6. find_unique(‘egg’, "immune", ‘feed’ 7. if __name_="_main_"; 8 main() Ovreur Unique characters in the wor Unique characters in the Unique characters in the wo Unique characters in the \ Unique characters in t The meth pps and Sets print(f'The unique and sorted words are {sor ted\list(set(words)))}") 4. def main() sentence = input("Enter a sentence ") 6 _unique_words(sentence) 7.if__name_—="_main_: & main’) Ourut Enter a sentence The man we saw saw a saw ‘The unique and sorted words are ["The,'a,'man’, ‘saw’, 'we'] : In the above program, the user-entered sentence ©) is split into a list of words based on space @. The words list is passed as an argument to the sei() method. The unique set of words returned by the sei() method is converted to a list and sorted @, <= Frozenset A frozenset is basically the same as a set, except that it is immutable. Once a frozenset is created, then its items cannot be changed. Since they are immutable, they can be used as members in other sets and as dictionary keys, The frozensets have the same functions as normal sets, except none of the functions that change the contents (update, remove, pop, etc) are available 1. >>> dir(frozenset) i {_and_!, ‘_class_', "_contains_' f _ge_!, “_getattribute_’, Lei a lent a '_teduce_ex_', '_repr_, “sizeof ’,'"str_," sub_’,'_subclasshook_’_xor_,, ‘copy’, difference’, intersection, i issubset’, ‘issuperset, 'symmetric_difference’,'union'] List of methods available forfrozenset Bd. For example, 1, >>> fs frozenset(("g’ "0", "0","d")) 2 >>> fs es and Sets 4 >>> animals {latte frozenset({e, 95g), horse) 5. >>> official languages_world = english'59, "french’:29, “spanish":21) 6, >>> frozenset(official_ languages world) frozenset('spanish’, french, english’) >>> frs= frozenset({"german")) 8. >>> official_languages_world = ("english"S9, french’:29, "spanish"21,frs:6) 9. >>> official languages. world ; english’ 59, "french 29, ‘spanish’ 21, frozenset( german): 6) The Frozenset type Bis used within a set @. Keys in a dietiona:y are retumed when a dictionary — is passed as an argument to frozensei() function ©), Frozenset is used as a key indictionary @.

You might also like