0% found this document useful (0 votes)
23 views32 pages

Python Programming Ch-5

The document provides an overview of strings and lists in Python, highlighting their definitions, operations, and methods. It explains how strings are immutable sequences of characters while lists are mutable collections of items that can store different data types. Additionally, it covers various functions and techniques for manipulating both strings and lists, including traversing, concatenation, and built-in methods.

Uploaded by

dp8260264
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)
23 views32 pages

Python Programming Ch-5

The document provides an overview of strings and lists in Python, highlighting their definitions, operations, and methods. It explains how strings are immutable sequences of characters while lists are mutable collections of items that can store different data types. Additionally, it covers various functions and techniques for manipulating both strings and lists, including traversing, concatenation, and built-in methods.

Uploaded by

dp8260264
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
Unit Strings and Lists Introduction to Strings String Operations ‘Traversing a String Strings Methods and Built-i Introduction to List and its Operations List Methods and Built-in Functions Nested and Copying Lists List as Arguments to Function Solved Questions Exercise Questions Program Exercise Functions Lists are part of core Python. Lists have a variety of uses. Like arrays, they are sometimes used to store data. However, lists do not have the specialized properties and tools that make arrays so powerful for scientific computing. So in general, we prefer arrays to lists for working with scientific data. For other tasks, lists work just fine and can even be preferable to arrays. Strings are lists of keyboard characters as well as other characters not on your keyboard. Dictionaries are like lists, but the elements of dictionaries are accessed in a different way than for lists. The clements of lists and arrays are numbered consecutively, and to access an element of a list or an array, you simply refer to the number corresponding to its position in the sequence. The elements of dictionaries are accessed by “keys”, which can be either strings or (arbitrary) integers (in no particular order). Dictionaries are an important part of core Python, 5.1 Introduction to Strings A string 1s a sequence of characters. It can be declared in python by using double. quotes. Strings are immutable, i.e., they cannot be changed, A string that contains no characters, often referred to as the empty string, string. It is simply a sequence of zero characters and is represented by *’ or quotes with nothing in between). 's still considered to be a (owo single or two double A string in python is an ordered sequence of characters, The point to be noted here is that a list 1s an ordered sequence of object types and a string is an ordered sequence of characters, This is the main difference between the two. Strings are created by enclosing a sequence of characte Fxamples of strings include "Marylyn”, “omg”, "good bad" within a pair of single or double quotes. 118 Python Programming Here is an example of string in python and how to print it # Assigning string to a variable | a = “This is a string” print (a) —_ | For declaring a string, we assign a variable to the string. The indexing of elements in a string starts from 0, Strings can be assigned variable names [a = “My dog's name is” “| b = “Bingo” Strings can be concatenated using the “+” operator: caat"t ab print(c) | Output : [Pity dog's name is Bingo™ In forming the string c, we concatenated three strings, a, b, and a string literal, in this case a space”, which is needed to provide a space to separate string a from b. String Operations ] Create list of strings To create a list of strings, first use square brackets { and ] to create a list. Then place the list items inside the brackets separated by commas. Remember that strings must be surrounded by quotes. Also remember to use =to store the list in a variable Example Z colors = [“red”, “blue”, “green”] It is also allowed to put each string on a separate line: animals = [ “deer”, | “beaver”, “cow” ia _ Print list of strings + To print a whole list of strings in one line, you can simply call the built-in print function, giving the list as an argument: colors = ["red”, “blue”, “green”] \ | print(colors) J} Output : | [‘red’, *bluc’, ‘green’) Strings and Lists 7 119 ‘Add strings to list When you already have a list of strings and you want to add unother string to it, you can use the append method: colors = [“red”, “blue”, “green"] [Link]("*purple”) print(colors) Output + [‘red’, ‘blue’, ‘green’, ‘purple’ You can also create a new list with only one string in it and add it to the current list colors = colors + [“silver"] Output = ['red’, “blue’, ‘green’, ‘purple’, ‘silver’] Print list as string If you want to convert a list to a string, you can use the built-in function repr to make a string representation of the list: products = ["shel?”, “drawer”] products_as_string = repr(products) print(products_as_string) Output : (shelf, “drawer’] Concatenate lists of strings You can use the + operator to concatenate two lists of strings, For example: red”, “bWue") colors colors2 = [“purple”, “silver"] | concatenated = colors! + colors? Print(concatenated) Output : ['red’, ‘blue’, ‘purple’ Check if string is in list You can use the in keyword to check if a list contains a string. This gives you a boolean value: either True or False. You can store this value somewhere, or use it directly in an if statement: silver’) [ colors = [“pink”, “cyan”] if “pink” in colors: print(“yes!”) has_cyan = “cyan” in colors print(has_cyan) 0 Python Programming | Output + yes! True | Sort list of strings To sort a list of strings, you can use the sort method: [numbers = [“one”. “two”, “three”, “four”] numbers, sort() | print(numbers) Output : four’, ‘one’; ‘three’, “two"] | You can also use the sorted() built-in function: = [“one", number: two”, “three”, “four"} numbers = sorted(numbers) | | _print(numbers) | Output + [four’, ‘one’, ‘three’, ‘two"] 7 Join list of strings . To join a hist of strings by another string, you need to call the join method on the string. giving your list as an argument, For example, if we have this list colors = (“red print(*, *join(colors)) 1 | 1 [_ Print" yoin(colors)) Output : red, blue, green rediblue|preen ‘Traversing a String You can use a for loop. range in Python, slicing operator, and a few more methods to traverse the characters in a string. Using for loop to traverse a string IC is the most prominent and straightforward technique to iterate strings. . Example : string! “Dou for char in string | print(char) [[serimgs and Lists va ‘Output = D i i | I. La Using range() to traverse a string Another quite simple way to traverse the string is by using Python runge function. This method lets us access string elements using the index Example Psringt rata” for ch in range(len(stringl)) | print(siring| {ch]) rr Output : 5 1 | a a Using Slice operator to traverse strings partially You cun traverse a string as a substring by using the Python slice operator ({]). It cuts off a substring from the orginal string and thus allows to traverse over it partially. ‘The {] operator has the following syntax: string [starting index : ending index : step value} To use this method, provide the starting and ending; indices along with a step value and then traverse the string. Below 1s the example code that iterates over the first six letters of a string. Example : String! = “Python Data Science” for char in stringl{0 : 6: II <0 os - 1p 122 Python Programming You cun take the slice operator usage further by using it to iterale over a string but leaving every alternate character. Check out the below example: Example string Python_Data_Science” for char in stringl{ : : 2): print(char) | 7 ae ji n e ‘Traverse string backward using slice operator If you pass a -ve step value and skipping the starting as well as ending indices, then you can iterate in the backward direction. Go through the given code sample. string_to_iterate = “Leaming” for char in string_to_iterate[ ©: -I]: print(char) Output e ie Using indexing to iterate strings backward ‘Strings and Lists [123] Slice operator first generates a reversed siring, and then we use the for loop to traverse it, Instead of doing it, we can use the indexing to iterate strings backward. Example = string! = Learning” ch = len(string!) = 1 while ch>= 0: print(string! {ch}) ch -=1 Python String Functions Let’s take a look at the various string functions in Python, 1) Stnng Replace This method is used to replace the string, which accepts two arguments, Example : lang = “Hello Selenium” prini([Link]("Selenium”, “Python”)) Output : [Helto Python 2) String Reverse ‘This method is used to reverse a given string Example : | tang = “Python” | print(”” join(reversed(lang))) Output : [nohtyP, 3) String Join 124 | This method returns the string concatenated with the elements of iterable. Python Programming | 2 32 | print(s1 join(s2)) Output : 1ABC2ABC3 4) String Split This method is used to split the string based on the user arguments Example : text = “Welcome to Python” print([Link]()) Output : {'Welcome’. ‘to’. ‘Python’] 5) String Length This method returns the length of the String. Fxample > [text = “Python” [LPrintilentiext)) Output = 6 6) String Compare This method is used to compare two strings. Example : sl s2 = “Python” if(s1 == 82): Python” print(“Both strings are equal”) ‘Output : Both strings are equal 7) String Lowercase This method is used to convert the uppercase to lowercase. [strings and Lists Example = text = “PYTHON™ print([Link]()) iput > < ~ python 7 8.3 Introduction to List and its Operations A list is @ sequential collection of Python data values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, except that the elements of a list can have different [Link] are one of the most powerful tools in python. 125 There i several ways to create a new list The simplest is to enclose the elements in square brackets. (Land [10, 20, 30, 40] 7 [*hello”, “how”, + “you") | ‘The first example is a list of four integers. The second is a list of three strings. As we said above. the elements of a list don’t have to be the same type. The following list contains a string. a float, an integer. and another list. ‘Types of lists Below are some examples of homogeneous and heterogeneous lists in python: Homogenous Lists: Heterogeneous Lists: “dog’ 2.2, horse") | Accessing an Item from the List list=[[Link]’,2.2,’horse’] print(list{1}) Output : dog = j ‘As mentioned earlier, that indexing starts from 0, so when index [1] is passed. it gives the result as “dog”. Similarly, if we pass the index, say [2], it will give the output 2.2 Lists are mutable, ie., they can be altered once declared. Example : Modifying lists L={l 2 “string”, 142] print L | 126 Python Programming [Link](o) print L [Link]) print L pant L{1] Output : “sinng’, 3] ‘string’. 3. 6] string’, 3] The last clement of this array is L[3], because L has 4 elements. The last element can also be accessed as L{-1]. no matter how many elements L has. and the next-to-last element of the list is L{-2]. ete. Example . “string” , 142] | prin) print(L{-1}) print (L{-2}) (a “string™. 3) string : } Individual elements of lists can be changed. For example: Ls, | prineLy L{O]=L{0}+2 L13=3.14159) print(L) + “string” , 142] ‘string’, 3] “string”, 3.14159] | Here we see that [Link] added to the previous value of L{0] and the value 3 was replaced by the floating, point number 3.14139. You can also add lists. ‘Strings and Lists [127] print(l.) | prinul+L) 10. [Link],5,8, 13) 10. 1, 1, 2.3, 5, 8, 13,0, 1, 1,2, 3, 5, 8, 13) Slicing lists You can access pieces of lists using the slicing feature of Python: Example : L = [10.0, ‘girls & boys’, (2+0)), 3.14159, 21) prin(L{1:4)) print(L{2:5}) print(L{2:]) | print [:2)) print(L{:}) print(L{1:-1]) | print(len(L.) Output : | [girls & boys’, (2+0)), 3.14159] {(2+0j), 3.14159, 21] [(2+0)), 3.14159, 21) (10.0, ‘girls & boys’] [10.0. “girls & boys’, (2+0}), 3.14159, 21} Ugirls & boys’, (240)), 3.14159] You access a subset of a list by specifying two indices separated by a colon Adding lists concatenates them, just as the “+” operator concatenates strings. This is a powerful feature of lists that we will use often. If the left slice index is, you can leave it out: similarly. if the right slice index is the length of the list, you can leave it out also. You can get the length of a list using Python’s len() function Creating and modifying lists Python has functions for ereating and augmenting lists. The most useful is the range function, which cun be used to create a uniformly spaced sequence of integers. The general form of the function is range({start,] stop[, step}) where the arguments are all integers; those in square brackets are optional. # makes a list of 10 integers from 0 to 9 ] | # makes a list of 10 integers from 3 to 12 | Lelist(range(0.10.2))_ # makes a list of 10 integers from 0 to 9 with increment 2 | ot) | Output : = - j 10. [Link].7, 8, 9) | ee 6.7.8, 9] | (0, 2. 4. 6. 8) | I 1 aa 4 5.4 List Methods and Built-in Functions allows you to join two lists together. This method is Method J Description Example Output ‘appendtx) “Adds an item (x) to the endof | a=["bee", "moth"] Thee’ moth’) | the list. This is equivalent print(a) ['bee’, ‘moth’, ‘ant’) | to aflen(a):] = (x). | aappend("ant") print(a) 4 ‘extendliterable) | Extends the ist by appending all | a= ("bee "moth"] Tee’, moth] | the items from the iterable. This | print(a) ['bee’, ‘moth’, ‘ant’, aextendi{"ant", "tty"}) print(a) tiv) equivalent to allen(a): iterable. insert») Inserts an item ata given a= [bee "moth'T [bee moth] position. The first argument is | print(a) bee’, moth’) the index of the element before | [Link](O,“ant") which to insert. For print(a) ‘example, [Link](O,x) inserts at | ainsert(2. "fy) the front of thelist, print(a) | remove) Removes the first item from the | a=["bee™, "moth, "ant") | (bee, moth, ant] list that has a value of x. Returns | print(a) ['bee’,‘ant’) an error if there is no such item. | [Link]("moth") printa) popilil) Removes the item atthe given | # Example I: No index | (bee, ‘moth’, ‘ant] position inthe lst, and returns | specified bee’, moth’) it. ffno indexis | as bee", "moth", "ant”) | ['bee’, ‘moth’, ‘ant'] specified, pop() removes and | print(a) returns the last item in the lst. | 2.p0p() print) # Example 2: Index specified a= ["bee", "moth, "ant" | print) { | @.pop(1) | prine(a) Removes all items from the list. Equivalent to dela: "bee", “moth”, “ant') Thee, ‘moth, ant] o_ 129 ‘Strings and Lists - accleart) fee print(a)_ Returns the position of the first_| a= ["bee™, “ant®, "moth", | 2 list item that has avaiue of x | “ant” 7 Raises a ValueError if there is no | print([Link]("ant")) | such item, | print([Link](“ant", 2)) | The optional | arguments start and end are interpreted as in the slice Notation and are used to limit the search to a particular Subsequence of the list. ~ countix) Returns the number of | a= [ibee",“ant’, “moth”, | 2 times x appearsin thelist. | “ant) 7 print([Link]("bee")) | 0 | print([Link]("ant™)) | print([Link](*")) sortikey=None, | Sortsthe tems ofthelstin a= [365,2.4,1) [0:2-3-45.4) reverse=False) | place. The arguments canbe | [Link]() 169.49 2D used to customize the | print(a) [arty ‘bee’. meth, ‘operation. wasp!) 5 key a= (3,6,5,2,4,3] | bee’ ‘wasp’, Specifies a function of one [Link](reverse=True) ‘butterfiy’] . argument that is used to extract | print(a) Ubutterfly’, ‘wasp’, ‘a comparison key from each lst gee) element. The default value a= ["bee", "wasp", | is None (compares the elements vant] directly). asort() reverse | print(a) Boolean value. ifsettoTrue, | then the list elements are a=["bee", “wasp”, Sorted as if each comparison “butterfly"] were reversed. asort{keyslen) print(a) a= "bee", "wasp", | "butterfiy" asort(key=len, reverse=True) : rint{a) reverse() Reverses the elements ofthe | a= (3,6,5,2,4,1) (1, 4,2,5, 6,3) list in place. areverse() ant’, ‘moth’, ‘wasp’, printia) ‘bee'] a= ["bee", "wasp", print(a) copy) Returns a shallow copy ofthe | # WITHOUT copy) (bee, wasp’, “moth, list. Equivalent to af}. a= ("bee ‘ant’) Use the copy() method when | “moth*] ('bee', wasp’, ‘moth’, you need to update the copy | b=a ‘ane’) without affecting the original | [Link]{"ant") list. If you don't use this method | print(a) {eg, if ou do something print(b) like 'st2 = list), then any_ ['bee', ‘wasp’, ‘moth’] bee’, wasp’, ‘math’, vant) Sa wee IT 130 ne | List Functions updates you do to list2 will also | # WITH copy() affect lista. : a= ["bee®, "wasp | The example at the side | “moth") demonstrates this. b= [Link]() baappend("ant”) prt) LT Bt Commonly Used Python List Functions ‘The following Python functions can be used on lists. Method Description 7 Output Tenis) / Returns the number ofitems | 3 in the list. Jane’) The lent) function can be used | print(len(a)) ‘on any sequence (such as a | string, bytes, tupie, list, or | range) or collection (such as a dictionary, set, or frozen set). | Tisti{iterabie)) The list() constructor returns a | print(istl) a | mutable sequence list of | print{list(}}) a elements. print(list({"bee", ['bee’, ‘moth’, 'ant’] The iterable argument is moth", "ant"))) {{’bee", ‘moth’, optional. You can provide any | print(list({["bee", ant’) sequence or collection (such | "moth"t, |"ant"})) ('b''e','e') asa string, list, tuple, set, (', ‘am, ‘2, tuple’) dictionary, etc). if no | a="bee" ['am', "', 'a', set’) argument is supplied, an | prind(list(a)) empty list 's returned. Strictly jasc", "am", speaking, list({iterable]) is "tuple") actually a mutable sequence | print(list(a)) type. max(arel, are2, | "args keyi) The key argument speciiies 3 one-argument crdering function like that usec for sort(). The default argument specifies an object to return if | a={1,2,3,4,5] the provided iterabie is empty. | b= (2,2, 3,4] If the iterable is empty | print(maxt,b) and default is not provised, a ValueEtror is raised | Hf more than one item shares | the maximum value, only the first one encountered is returned. ‘of two or more arguinents. | print(max(a)} i | | print(max(a}) Tmax(iterable, | Returns the largest tern roth *L key, defautt}) | iterable (eg, list) or the iargest | “ant"] wasp or (1,2,3,4,5) [Strings and Lists [131 minfiterable, Returns the smallestitem in [a=|["bee","moth’, | bee *[, key, default]) | an iterable (eg, list) or the | "wasp"] ant or smallest of two or more print(rnin(a)} (2,2,3,4] | min(argt, arg2, | arguments *args|, key]) ‘The key argument specifiesa_| a=("bee", "moth", one-argument ordering | rant’ function Ike that used print(min(a)) for sort). | | The default argument a=(1,2,3,4,5] specifies an object to return if | b= [1, 2, 3,4) the provided iterabe is empty. | print(min(a, b)) If the iterable is empty | | and defauitis not provided, | a ValueError is raised. | !f more than one item shares ‘the minimum value, only the first one encountered is returned, | range(stop) Represents an immutable | print(list(range(10))) | {0, 1,2,3,4,5,6,7, or Sequence of numbers andis | print(list(range(1,11))) | 8, 9} a range(start, stop[, | commonly used for looping a | print(list(range(51,56))) | 1, 2, 3,4, 5,6, 7,8, step} ‘specific number of times | print(list(range(1,11,2))) | 9, 10) in for loops, (51, 52, 53, 54, 55] Itcan be used along (2,3,5,7,9] | with list() to return alist of | items between a given range. Strictly speaking, range() is actually a mutable sequence ‘ype. 1) tend The Python list method ien() returns the size(number of items) of the list by calling the list object’s own length method. It takes in a list object as an argument and doesn’t have a side effect on the list. Syntax —— [en(s) Where s can be either a sequence or collection. Example : Write a function that computes and returns the size/length of a list. j= # defined an empty list, 12 = [543,611 # define a list of 4 elements 13 = [4.3] {0.1],.3]] # define a list of 3 elements(tists | print(*Lt en: *, len(il)) | print(L2 ten: *, len(I2)) | print(“L3 ten: “, len(13)) [32 Python Programming Output : LI ten | L2 len: [b3 ten: 3 2) Histo) list() is actually a Python built-in class that creates a list out of an iterable passed as an argument. AS it will be used a lot throughout this tutorial, we will take a quick look at what this class offers, syntax Tist({terable}) The bracket tells us that the argument passed to it is optional. ‘The list() function is mostly used to: * Convert other sequences or iterables to a list. + Create an empty list ~ In this case, no argument is given to the function. Example 2 : Convert tuple, dict to list, and create an empty list t= (435.0.1) —— # define a tuple 's = “hello world!’ # define a string d= {‘name’:"Jitendra”"age":40,"gender”:"Male”)} # define a dict # convert all sequences to list List, s list, d_tist = list(t), lists) list(d) # create empty list | empty_list = list() print(“tuple_to_list: “, list) print(“string_to_list: “, s_list) print(“dict_to_list: *, d_list) | print(“empty_tist: “. empty_list) ‘Output : tuple_to_list: {4, 3, 5.0, 1] owt, fo! string to_list: ['h’, ‘e', ‘I’, dict to_list: [‘name’, ‘age’, “gender’] empty_list: {] . | Note : Converting a dictionary using list(dict) will extract all its keys and create a list. That is why we have the output ["name’ ‘age’.’gender’} above. If we want to create a list of a dictionary's values instead, we'll have to access the values with [Link](), Strings und Lists 133 3) ranged) The Python list function ranged) takes in some integers as arguments and generates a list of imegers Syntax [start Jsiopl step) Where * start: Specifies where to start generating integers for the list. * stop: Specifies where to stop generating integers for the list. ‘+ step: Specifies the incrementation From the syntax above, start and step are both optional and they default 10 0 and I respectively, Example 3 : Create a sequence of numbers from 4 to 20, but increment by 2 and print it start = 4 # define our stant number end = 20 # define out end number step = 2 # define out step number print("Range of numbers:”) f= range(start, end, step) # print items in the range object. for item in r: | print(item) Output : [ Range of numbers: | | 4 6 |8 16 18 4) sumo The Python sum() function adds all items in an iterable and returns the result Syntax Sumiterable{.start)) 134] Python Programming | Where + The iterable contains items to be added from left to right + start is a number that will be added to the returned value The iterable’s tems and start should be numbers. If sturt is not defined, it detaults to zero(0) Example 4: Sum items from a list | >>> sumi19,3,2,5,1,-9]) fu a : J Example S$ © Stan with 9 and add all items from the hist 19.3.2,5,1,-9], [ >>psum({[Link].1-9}, 9) 0 5) mind) ‘The Python mim) function retums the smallest item in a sequence. ‘Symtax : Liminiterable[ key, defautt)) Where * iterable here will be a list of items. + key here specifies a function of one argument that is used to extract a comparison key from each list element + default here specifies a value that will be retumed if the iterable is empty. Example 6 : Find the smallest number in the list (4,3.9,10,33,90]. | >>> numbers = ([Link].33.90] | >>> min(numbers) 3 6) maxi) The Python max() function retums the highest item in a sequence. Syntax [ [Link], default) Where * iterable here will be a list of items. + key here specifies a function of one argument that is used to extract a comparison key from cach list clement + default here specifies a value that will be returned if the iterable is empty. [Strings and Lists Example 8 Find the largest number in the hat [4.19 10,1090] [555 numbers = T9013 90) | >>> maxcnumbers | 90 7) sorted() The Python sorted’) method returns 4 new sorted jist of stems trom un Keruble. Syntax I sorted{iterable|,[Link]|) Where + iterable here will be a list of suems kkey here specifies a function of one argument that 1s used to extract a companson key from each list elemeni. reverse is a bool that specifies ifthe sorting should he done in axcending(Fahe) or dexcendimg(True) order. It defaults to False Example 9 : Sort the list (4,3,10,6.21,9,23} in descending order [ >>> numbers = [4.3,10,6.21,9.23) | s>>sortedinumbers, reverse=True) (23.21. 10. 9, 6, 4, 3) 8) reverved() The Python reversed() function returns a reverse iterator in which we can request the next value or iterate through until we hit the end. Syntax : Feversed{iterator) Example 11: Find the reverse order of the list. [>>> numbers = (4,3,10,6.21,9.23) >>> list(reversed(numbers)) 2 123, -9, 21, 6, 10, 3, 4] . | Note : We should note the following, © As reversed) returns a generator expression, we can use list) to create the list of items. +The Python reversed() function is similar to the list method reverse(). However, the latter reverses the list in-place. + Using slicing(al::-1]), we can reverse a list similar to the reversed) function 9) enumerate’) ‘The Python enumerate() function returns an enumerate object in which we can request the next value oF iterate through until we hit the end, (se [ Python Programming ‘Syntax = ‘enumerate(sequence, start=0) Each next item of the retumed object is u tuple (count, item) where the count starts from 0 as default, and the item is gotten from iterating through the iterator: Example 12 : Enumerate the hist of names [“eyong”."kevin™."enow starting from 3 and retums a list of tuples such as (count, item). Payamba""derick"} with the count >>> names = [“eyong”, Kevi >>>list(enumerate(names, 3)) ((3, ‘eyong’), (4, *kevin’), (5, ‘enow"), (6, ‘ayamba’), (7, ‘derick”)} 10) zip0 ‘The Python zip() function returns an iterator that contains an aggregate of each item of the iterables. Syntax : zip(*iterables) Where the * indicates that the zipQ function can take any number of iterables Example 13 : Add the i-th item of each list. 11 = (46.19) < 12 = ([Link]) result = (] # define an empty list to hold the result | # aggregate each item of the lists # for each iteration, item and item? comes from II and 12 respectively for iteml, item2 in zip(lt, 12): [Link](itemI + item2) # add and append prin(“RESULT: “, result) ‘Output : m RESULT: _[13. 6, 3. 16] Note: It is important to note that this resulting iterator stops when the shortest iterable argument is exhausted. Example : N= 34.71 12 = (0.1) result = {] # define an empty list to hold the result # aggregate each item of the lists # for each iteration, item1 and item2 comes from 11 and 12 respectively Strings and Lists for Weml, item2 in zip(lt, 12» [Link](item! + item2) # add and append. print(RESULT: “, result) Output [RESULT (3. 5) The result above didn’t include 7 from I1. This is becuuse 12 is 1 item shorter than 12 11) map() ‘The Python map() function maps function to each item of iterables and returns an iterator. Syntax map(lunction, werable,..) This function is mostly used when we want to apply a function on each item of iterables but we don't want to use the traditional for loop. Example 14 : Add 2 to each item of the list |= [Link].2.3.6) | result = [] # create empty list to hold result # iterate over the list for item in I: resultappend(item+2) # add 2 and append print(“MAP: “, result) Output : [ MAP: 8, 6.10.11, 4, 5, 8) Note: The map() function can take any number of iterables given that the function argument has an equivalent number of arguments to handle each item from each iterable. Like zip(). the iterator stops when the shortest iterable argument is exhausted. 12) filter() ‘The Python filter) method constructs an iterator from the items of iterables that satisfy a certain condition Syntax [iitterunction, iterabley The function argument sets the condition that needs to be satisfied by the items of the iterable. Items that do not satisfy the condition are removed. ; Example 15 : Filter out the names with length smaller than 4 from the list [ion "petter” "job", paul”'mat”) Example : names = [“john","petter”,”job”."paul”,"mat") result=list(filter(lambda name: len(name) >=4, names)) print(-MAP: *, result) Python Programming = (FT) / 2024 / 18 138 Python Programming Output : MAP!_[‘john’, ‘petter’. “paul'} 13) iter() The Python iter() function converts an iterable into an iterator in which we can request the next value or iterate through until we hit the end. Syntax (object{ sentinel) 7 iter(objeci| sentinel) 7 Where * abject can be represented differently bused on the presence of sentinel. It should be an iteruble or sequence if a sentinel is not provided or a callable object otherwise. ‘* sentinel specifies a value that will determine the end of the sequence. Example 16 : Convert the list [‘a’,'b’,'c’d','e"] into an iterator and use next() to print each value, MWe [ab ‘d’c"] # create our list of letters | iter list = iter(11) # convert list to iterator | printinext(iter_list)) # access the next item print(next(iter_tist)) | | printinexttiter_list)) Print(next(iter_list)) Output : b Ld 14) all The Python all() function returns True if all the elements of an iterable are true, or if the iterable # empty. Syntay, [lcterable) Note + In Python, False: empty list((]), strings("). dict({}): zero(0), None, etc are all false. + Since the Python all() function takes in an iterable argument, if an empty list is passed as an ‘argument. then it will retum True. However, if a list of an empty fist is passed, then it will return False. Example 18: Check if all items of a list are true | L= (3y'hello’0, -2] # note that a negative number 1s not false | printa() ‘Strings and. Lists 139 Output + (Fase J In the example above, the result is False as element 0 in the list is not true. 15) any() The Python any() function retums True if at least one item of the iterable is true. Unlike all), it will return False if the iterable is empty Syntax [Lanytiterable) Example 19: Check if at least one item of the list {‘hi' [4,9],-4,True] is true. s[)-( },False,0,None] # all is false print(any(t)) | printany(12)) Output : {True False Nested and Copying Lists Nested list is a list having another list inside it. Create a Nested List An ed list is created by placing a comma-separated sequence of sublists. ", L'bb’, {‘cce", “ddd’}, ‘ee’, *f"], *g', *h’) ‘Access Nested List Items by Index You can access individual items in a nested list using multiple indexes. ‘The indexes for the items in a nested list are illustrated as below: oO 4 pnnL{2}) = [ee “dd, Fece’. “AP HL. “g’. *h’] Output [rce", “dd, [‘ece", “f1']] | prin(LI2112)) Output : Vece’. fT] print(L(21(2}10}) Output : cece ‘Change Nested List Item Value ‘You can change the value of a specific item in a nested list by referring to its index number. L= Ca’ [bb ‘ce’). a] Li = 0 print(L) Outpu Ca’, Cob’, 0}, “a'] Add items to a Nested list To udd_new values to the end of the nested list, use append() method. L=[‘a, [*bb’, *cc’], ‘d") L{[Link](*xx’) print(L) Outpui ['a’, [*bb’, ‘co*, ‘xx'], ‘d"] L= [a [bb ‘cc'), “a L{1].insert(0, xx") print(L) When you want to insert an item at a specific position in a nested list, use insert) method. Output : Ca’, ['xx', ‘bb’, ‘cc'], a’) You can merge one list into another by using extend() method. L= [a (bY ‘cc'), “'] Li Jextend((1,2.3)) |_pnat(L) Strings and Lists Output : ane fra’, Ub’, “ce", 1, 2, 3}, “A'] 144 Remove items from a Nested List If you know the index of the item you want, you can use pop() method. It modifies the list and retums the removed item L = ['a’, ("bb “cc, “dd’]. ‘e') x = L{I].pop(!) prin) # removed item printix) Output = Tra’, [bb “da ], *e] 1 cc. If you don't need the removed value, use the del statement. L =a’, ["bb’, ‘ce’, “dd’], “e'] del LINEN print(L) Output [ha Pbpb", sda", “e") If you're not sure where the item is in the lis, use remove(} method to delete it by value. L = ['a’, ["bb’, ‘cc’, ‘dd’], ‘e") Ly Jeremovet‘ec") , prini(L) Output : Fa’, bb’, “dd’), “e") al Find Nested List Length You can use the built-in lenQ function to find how many items a nested sublist has L= [a bb’, “ec'), “e'] print(len(.)) print(len(L{1)) | Output : 3 2 Iterate through a Nested List To iterate over the items of a nested list, use simple for loop. 142 | L = (Ul. 2. 34. 5, 6117, 8, 9) for Hist in L [for number in Tist: |__printinumber, end=" *) Output : [123456789 Various other ways to Create a Nested Listsin Python There are many approaches to create a list of lists, Here, we are using the append() method and list comprehension technique to create a list of lists Create a list of lists using the append() method in Python In this example, we are using an append() method that used to append a list into a list as an element. we created two lists and append them into another list using the append() method and print the list which is actually a list of lists. # Take two lists ] 1234) list2 = [[Link]] listl = list3 = [] # Take an empty list # make list of lists [Link](list) [Link](tist2) print(list3) Output : I. 2.3, 4), (5, 6, 7. 81) Create a list of lists using the list initializer in Python The list initializer syntax is used to create a list in Python, We can use this technique to create a list of lists by passing lists as elements into the list initializer. See the code and output # Take two lists. U.234) 6.7.8] list list2 | # make list of lists | hist3 = [listl, hist2] # Display result ) | Output : = HH. 2. 3. 4h 15,6. 7. 811 | [+] We can use for loop to create a list of lists in Python. We used the append() method inside the loop to add the element into the list to form a list of lists. See the code and output. [ists = 11 = | # make list of lists | Create @ list of lists using for-loop in Python for i in range(2): | # append list | [Link]({]) for j in range(S): | listsfi].append() # Display result print(lists) Output : U0. 1. 2,3, 4), 0. 1. 2, 3, 4) Create a list of lists using list comprehension in Python If you are comfortable with list comprehension then use it to make a list of lists as we did in the below code example. See the code and output here # Take a list list = ['Apple’/Mango’ ’Orange’} u # make list of lists hist lists = [{val] for val in list) # Display result print(lists) Output : {[Apple’}, (*Mango’}, ('Orange"]] How to access elements from a list of lists in Python We can access elements by using an index. The list index starts from © and end to n-1 where n is the length of the list. Here, we used 0 index to get the first element of the list. # Take a list Hist = [‘Apple’ /Mango’ ‘Orange'] | tists = 1) | # make list of lists | lists = {{val] for val in list] | [# Display result [=] Python Programming printlists) # Access Element s(O)) print prin(lists{2]) Output IP Apple’), (*Mango’), [Orange )) UApple’) Orange") List as Arguments to Function You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. Eg. if you send a List as an argument, it will still be a List when it reaches the fun Example : def my_function(food): 7 for x in food: | printix) fruits = (“apple”, “banana”, “cherry”] my_function( fruits) Output apple banana cherry | Solved Questions 1. Mention the features of lists in python Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed with in square brackets ({]). To some extent, lists are similar to arrays in C One difference between them is that all theitems belongingto a list can beof different data type The values stored in a list can be accessed using the slice operator ({] and {:]) with indexes starting at 0 in the beginning of the list and working their way 10 end-I. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example list = [‘abed’, 786 , 2.23,"john’, 70.2 Iprint list{0] olp abed ee — [Siem and tise a] What is fen function and explain how itis used on Sirings with an example, The len function. when applied to 4 string, returns the number or character in a string. Example + >ssbooks'Problem Solvingand Python Programming: >>al en(book) 38 >> 3. Explain about string slicing with examples. > A substring of a string is obtained by taking a slice. The operator [n:m] returns the part of the string from the nth character to the mth character, including the first but excluding the last >p>book='Problem Solvingand Python Programming'>>>print(book(0:7]) Problem >>ppnnt(book[21:27]) python 4, What are the two operators that are used in string functions ? The in operator tests for membership, >»'Viin VRB* ‘True >>>'S' in VRB* >>>Palse ‘The not in operator returns the logical opposite results of in operator. >>>"x* not in VRB* True 5. What is the use of strupper() and strJower() functions in string ? The functions strupper() and strlower() will return a string with all the letters of original string converted to upperor lower case letters. >>>ss="VRBPublishers’ >>>print(ss, upper()) VRB PUBLISHERS >>print([Link]()) Vrb publishers 6. Explain string comparison with an example. ‘The comparison operator works on string to check if two strings are equal RBPublishers* VRB Publishers‘ Print( Both areEqual") Both are Equal Python Progeamming (IT) / 2021 / 19 146 Python Programming How to split strings and what function is used to perform that operation ? The [Link]() method is used to split strings up >>>book="Problem Solving and Python Programming >>>print([Link]()) | Problem’, Solving’, ind’, Python‘, Programing"| 7. What are tuples in Python? A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists however, tuples are enclosed within parentheses, 8. What is the difference between tuples and lists in Python? The main differences between lists and tuples are — Lists are enclosed in brackets ({ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read- only lists. 9. Explain what is range() function and how it is used in lists 2 The range function returns an immutable sequence object of integers between the given start integer to thestop intege range([Link],{step]) >>ef or lin range( 1.10.2), - yy 10. How lists are updated in Python ? The append() method is used to add elements to alist. 123,°VR B'] Syntax : listappend(obj) Li List append(2017) Print(“Updat ed List: . List) Output: Updated List: [123 VRB*.2017} 11. Write a few methods that are used in Python Lists. () 4) append()- add an element to end of list b)_ insert()-insert an item at the defined index | ©) remove()-removes an item from the list | @)clear()-removes all items from the list ©) reverse()-reverse the order of items in the list 12. What are the advantages of Tuple over List ? PY Tupleis used for heterogeneous data types and list is used for homogeneous dati types. * Since tuple are immutable, iterating through tuple is faster than with list Tuples that contain immutable elements can beused as keyfor dictionary. Implementing data that doesn‘t change as a tuple remains write-protected. Strings and Lists 147 Questions + Explain the different string formats available in Python with examples + Discuss the following list functions a) len() b) sum() c) any() d) all() e) sorted() Enumerate the list and its methods with example Explain the following list methods with an example. a) append() b) extend() c) insert() d) index() e) sort() Program Exe1 + Check if the items in the list are sorted in ascending or descending order and print suitable messages accordingly. Otherwise, print “Iems in list are not sorted” Print characters from a string that are present at an even index number Remove first n characters from a string the resultant matrix Write Python program to sort words in a sentence in decreasing order of their length. Display the sorted words along with their length. Check if the first and last number of a list is the same Given a two list of numbers, write 2 program to create a new list such that the new list should contain odd numbers from the first list and even numbers from the second list. Given fisth = (10, 21 5, 30. 35] list2 = [40, 45, 60, 75, 90] Expected Output: resull list: [25, Write Pythonic code to multiply two matrices using nested loops and also perform transpose of cd Mathematics Communication Skills in English Sports and Yoga | Python Programming Introduction to IT Systems | | a}o]r| + fp Static Webpage Design we) eae [Link] | ‘ATULSBOOKS. aay l) a nN Ny STALL Feretia vial viajar) MIEZTUSI 9, Elo! aye! wieeasdel 21d2 aaa, ee wai wdlanaal 210 Rriaieti yenojer yectsiol zieof | sveictotl aa asaael urdell yectsieil de una 8. 19BN978~ i 85 i i

You might also like