Add List Items Adding list items in Python implies inserting new elements into an existing list. Lists are mutable, meaning they can be modified after creation, allowing for the addition, removal, or modification of their elements. Adding items in a list typically refers to appending new elements to the end of the list, inserting them at specific positions within the list, or extending the list with elements from another iterable object. We can add list items in Python using various methods such as append(), extend() and insert(). Let us explore through all these methods in this tutorial. Adding List Items Using append() Method The append() method in Python is used to add a single element to the end of a list. We can add list items using the append() method by specifying the element we want to add within the parentheses, like my_list.append(new_item), which adds new_item to the end of my_list. Example In the following example, we are adding an element “e” to the end of the list “list1” using the append() method − Open Compiler Output Following is the output of the above code − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Adding List Items Using insert() Method The insert() method in Python is used to add an element at a specified index (position) within a list, shifting existing elements to accommodate the new one. We can add list items using the insert() method by specifying the index position where we want to insert the new item and the item itself within the parentheses, like my_list.insert(index, new_item). Example In this example, we have an original list containing various items. We use the insert() method to add new elements to the list at specific positions − Open Compiler After appending ‘Chemistry’ to the list, we get the following output − Then, by inserting ‘Pass’ at the index “-1”, which originally referred to 69.75, we get − We can see that “Pass” is not inserted at the updated index “-1”, but the previous index “-1”. This behavior is because when appending or inserting items into a list, Python does not dynamically update negative index positions. Adding List Items Using extend() Method The extend() method in Python is used to add multiple elements from an iterable (such as another list) to the end of a list. We can add list items using the extend() method by passing another iterable containing the elements we want to add, like my_list.extend(iterable), which appends each element from the iterable to the end of my_list. Example In the below example, we are using the extend() method to add the elements from “another_list” to the end of “list1” − Open Compiler Output Output of the above code is as follows −
Change List Items
Change List Items List is a mutable data type in Python. It means, the contents of list can be modified in place, after the object is stored in the memory. You can assign a new value at a given index position in the list Syntax Example In the following code, we change the value at index 2 of the given list. Open Compiler It will produce the following output − Change Consecutive List Items You can replace more consecutive items in a list with another sublist. Example In the following code, items at index 1 and 2 are replaced by items in another sublist. Open Compiler It will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Change a Range of List Items If the source sublist has more items than the slice to be replaced, the extra items in the source will be inserted. Take a look at the following code − Example Open Compiler It will produce the following output − Example If the sublist with which a slice of original list is to be replaced, has lesser items, the items with match will be replaced and rest of the items in original list will be removed. In the following code, we try to replace “b” and “c” with “Z” (one less item than items to be replaced). It results in Z replacing b and c removed. Open Compiler It will produce the following output −
Access List Items
Access List Items In Python, a list is a sequence of elements or objects, i.e. an ordered collection of objects. Similar to arrays, each element in a list corresponds to an index. To access the values within a list, we need to use the square brackets “[]” notation and, specify the index of the elements we want to retrieve. The index starts from 0 for the first element and increments by one for each subsequent element. Index of the last item in the list is always “length-1”, where “length” represents the total number of items in the list. In addition to this, Python provides various other ways to access list items such as slicing, negative indexing, extracting a sublist from a list etc. Let us go through this one-by-one − Accessing List Items with Indexing As discussed above to access the items in a list using indexing, just specify the index of the element with in the square brackets (“[]”) as shown below − Example Following is the basic example to access list items − Open Compiler It will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Access List Items with Negative Indexing Negative indexing in Python is used to access elements from the end of a list, with -1 referring to the last element, -2 to the second last, and so on. We can also access list items with negative indexing by using negative integers to represent positions from the end of the list. Example In the following example, we are accessing list items with negative indexing − Open Compiler We get the output as shown below − Access List Items with Slice Operator The slice operator in Python is used to fetch one or more items from the list. We can access list items with the slice operator by specifying the range of indices we want to extract. It uses the following syntax − [start:stop] Where, If we does not provide any indices, the slice operator defaults to starting from index 0 and stopping at the last item in the list. Example In the following example, we are retrieving sublist from index 1 to last in “list1” and index 0 to 1 in “list2”, and retrieving all elements in “list3” − Open Compiler Following is the output of the above code − Access Sub List from a List A sublist is a part of a list that consists of a consecutive sequence of elements from the original list. We can access a sublist from a list by using the slice operator with appropriate start and stop indices. Example In this example, we are fetching sublist from index “1 to 2” in “list1” and index “0 to 1” in “list2” using slice operator − Open Compiler The output obtained is as follows −
Lists
Python Lists List is one of the built-in data types in Python. A Python list is a sequence of comma separated items, enclosed in square brackets [ ]. The items in a Python list need not be of the same data type. Following are some examples of Python lists − List is an ordered collection of items. Each item in a list has a unique position index, starting from 0. A list in Python is similar to an array in C, C++ or Java. However, the major difference is that in C/C++/Java, the array elements must be of same type. On the other hand, Python lists may have objects of different data types. A Python list is mutable. Any item from the list can be accessed using its index, and can be modified. One or more objects from the list can be removed or added. A list may have same item at more than one index positions. Accessing Values in Lists To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example − Open Compiler When the above code is executed, it produces the following result − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Updating Lists You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example − Open Compiler When the above code is executed, it produces the following result − Delete List Elements To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example − Open Compiler When the above code is executed, it produces following result − Note − remove() method is discussed in subsequent section. Python List Operations In Python, List is a sequence. Hence, we can concatenate two lists with “+” operator and concatenate multiple copies of a list with “*” operator. The membership operators “in” and “not in” work with list object. Python Expression Results Description [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 Indexing, Slicing, and Matrixes Because lists are sequences, indexing and slicing work the same way for lists as they do for strings. Assuming following input − Python Expression Results Description L[2] SPAM! Offsets start at zero L[-2] Spam Negative: count from the right L[1:] [‘Spam’, ‘SPAM!’] Slicing fetches sections Python List Methods Python includes following list methods − Sr.No. Methods with Description 1 list.append(obj)Appends object obj to list. 2 list.clear()Clears the contents of list. 3 list.copy()Returns a copy of the list object. 4 list.count(obj)Returns count of how many times obj occurs in list 5 list.extend(seq)Appends the contents of seq to list 6 list.index(obj)Returns the lowest index in list that obj appears 7 list.insert(index, obj)Inserts object obj into list at offset index 8 list.pop(obj=list[-1])Removes and returns last object or obj from list 9 list.remove(obj)Removes object obj from list 10 list.reverse()Reverses objects of list in place 11 list.sort([func])Sorts objects of list, use compare func if given Built-in Functions with Lists Following are the built-in functions we can use with lists − Sr.No. Function with Description 1 cmp(list1, list2)Compares elements of both lists. 2 len(list)Gives the total length of the list. 3 max(list)Returns item from the list with max value. 4 min(list)Returns item from the list with min value. 5 list(seq)Converts a tuple into list.
String Exercises
Example 1 Python program to find number of vowels in a given string. Open Compiler It will produce the following output − Example 2 Python program to convert a string with binary digits to integer. Open Compiler It will produce the following output − Change mystr to ’10, 101′ Example 3 Python program to drop all digits from a string. Open Compiler It will produce the following output − Exercise Programs
String Methods
Python’s built-in str class defines different methods. They help in manipulating strings. Since string is an immutable object, these methods return a copy of the original string, performing the respective processing on it. The string methods can be classified in following categories − Case Conversion Methods This category of built-in methods of Python’s str class deal with the conversion of alphabet characters in the string object. Following methods fall in this category − Sr.No. Method & Description 1 capitalize()Capitalizes first letter of string 2 casefold()Converts all uppercase letters in string to lowercase. Similar to lower(), but works on UNICODE characters alos 3 lower()Converts all uppercase letters in string to lowercase. 4 swapcase()Inverts case for all letters in string. 5 title()Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase. 6 upper()Converts lowercase letters in string to uppercase. Alignment Methods Following methods in the str class control the alignment of characters within the string object. Sr.No. Methods & Description 1 center(width, fillchar)Returns a string padded with fillchar with the original string centered to a total of width columns. 2 ljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns. 3 rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns. 4 expandtabs(tabsize = 8)Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided. 5 zfill (width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero). Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Split and Join Methods Python has the following methods to perform split and join operations − Sr.No. Method & Description 1 lstrip()Removes all leading whitespace in string. 2 rstrip()Removes all trailing whitespace of string. 3 strip()Performs both lstrip() and rstrip() on string 4 rsplit()Splits the string from the end and returns a list of substrings 5 split()Splits string according to delimiter (space if not provided) and returns list of substrings. 6 splitlines()Splits string at NEWLINEs and returns a list of each line with NEWLINEs removed. 7 partition()Splits the string in three string tuple at the first occurrence of separator 8 rpartition()Splits the string in three string tuple at the ladt occurrence of separator 9 join()Concatenates the string representations of elements in sequence into a string, with separator string. 10 removeprefix()Returns a string after removing the prefix string 11 removesuffix()Returns a string after removing the suffix string Boolean String Methods Following methods in str class return True or False. Sr.No. Methods & Description 1 isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. 2 isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise. 3 isdigit()Returns true if the string contains only digits and false otherwise. 4 islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. 5 isnumeric()Returns true if a unicode string contains only numeric characters and false otherwise. 6 isspace()Returns true if string contains only whitespace characters and false otherwise. 7 istitle()Returns true if string is properly “titlecased” and false otherwise. 8 isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise. 9 isascii()Returns True is all the characters in the string are from the ASCII character set 10 isdecimal()Checks if all the characters are decimal characters 11 isidentifier()Checks whether the string is a valid Python identifier 12 isprintable()Checks whether all the characters in the string are printable Find and Replace Methods Following are the Find and Replace methods in Python − Sr.No. Method & Description 1 count(sub, beg ,end)Counts how many times sub occurs in string or in a substring of string if starting index beg and ending index end are given. 2 find(sub, beg, end)Determine if sub occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise. 3 index(sub, beg, end)Same as find(), but raises an exception if str not found. 4 replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given. 5 rfind(sub, beg, end)Same as find(), but search backwards in string. 6 rindex( sub, beg, end)Same as index(), but search backwards in string. 7 startswith(sub, beg, end)Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring sub; returns true if so and false otherwise. 8 endswith(suffix, beg, end)Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise. Translation Methods Following are the Translation methods of the string − Sr.No. Method & Description 1 maketrans()Returns a translation table to be used in translate function. 2 translate(table, deletechars=””)Translates string according to translation table str(256 chars), removing those in the del string.
Escape Characters
Escape Character An escape character is a character followed by a backslash (\). It tells the Interpreter that this escape character (sequence) has a special meaning. For instance, \n is an escape sequence that represents a newline. When Python encounters this sequence in a string, it understands that it needs to start a new line. Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. In Python, a string becomes a raw string if it is prefixed with “r” or “R” before the quotation symbols. Hence ‘Hello’ is a normal string whereas r’Hello’ is a raw string. Example In the below example, we are practically demonstrating raw and normal string. Open Compiler Output of the above code is shown below − In normal circumstances, there is no difference between the two. However, when the escape character is embedded in the string, the normal string actually interprets the escape sequence, whereas the raw string doesn’t process the escape character. Example In the following example, when a normal string is printed the escape character ‘\n’ is processed to introduce a newline. However, because of the raw string operator ‘r’ the effect of escape character is not translated as per its meaning. Open Compiler On running the above code, it will print the following result − Escape Characters in Python The following table shows the different escape characters used in Python – Sr.No Escape Sequence & Meaning 1 \<newline>Backslash and newline ignored 2 \\Backslash (\) 3 \’Single quote (‘) 4 \”Double quote (“) 5 \aASCII Bell (BEL) 6 \bASCII Backspace (BS) 7 \fASCII Formfeed (FF) 8 \nASCII Linefeed (LF) 9 \rASCII Carriage Return (CR) 10 \tASCII Horizontal Tab (TAB) 11 \vASCII Vertical Tab (VT) 12 \oooCharacter with octal value ooo 13 \xhhCharacter with hex value hh Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Escape Characters Example The following code shows the usage of escape sequences listed in the above table − Open Compiler It will produce the following output −
String Formatting
String formatting in Python is the process of building a string representation dynamically by inserting the value of numeric expressions in an already existing string. Python’s string concatenation operator doesn’t accept a non-string operand. Hence, Python offers following string formatting techniques − Using % operator The “%” (modulo) operator often referred to as the string formatting operator. It takes a format string along with a set of variables and combine them to create a string that contain values of the variables formatted in the specified way. Example To insert a string into a format string using the “%” operator, we use “%s” as shown in the below example − Open Compiler It will produce the following output − Using format() method It is a built-in method of str class. The format() method works by defining placeholders within a string using curly braces “{}”. These placeholders are then replaced by the values specified in the method’s arguments. Example In the below example, we are using format() method to insert values into a string dynamically. Open Compiler On running the above code, it will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Using f-string The f-strings, also known as formatted string literals, is used to embed expressions inside string literals. The “f” in f-strings stands for formatted and prefixing it with strings creates an f-string. The curly braces “{}” within the string will then act as placeholders that is filled with variables, expressions, or function calls. Example The following example illustrates the working of f-strings with expressions. Open Compiler The output of the above code is as follows − Using String Template class The String Template class belongs to the string module and provides a way to format strings by using placeholders. Here, placeholders are defined by a dollar sign ($) followed by an identifier. Example The following example shows how to use Template class to format strings. Open Compiler It will produce the following output −
String Concatenation
Concatenate Strings in Python String concatenation in Python is the operation of joining two or more strings together. The result of this operation will be a new string that contains the original strings. The diagram below shows a general string concatenation operation − In Python, there are numerous ways to concatenate strings. We are going to discuss the following − String Concatenation using ‘+’ operator The “+” operator is well-known as an addition operator, returning the sum of two numbers. However, the “+” symbol acts as string concatenation operator in Python. It works with two string operands, and results in the concatenation of the two. The characters of the string on the right of plus symbol are appended to the string on its left. Result of concatenation is a new string. Example The following example shows string concatenation operation in Python using + operator. Open Compiler It will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Concatenating String with space To insert a whitespace between two strings, we can use a third empty string. Example In the below example, we are inserting space between two strings while concatenation. Open Compiler It will produce the following output − String Concatenation By Multiplying Another symbol *, which we normally use for multiplication of two numbers, can also be used with string operands. Here, * acts as a repetition operator in Python. One of the operands must be an integer, and the second a string. The integer operand specifies the number of copies of the string operand to be concatenated. Example In this example, the * operator concatenates multiple copies of the string. Open Compiler The above code will produce the following output − String Concatenation With ‘+’ and ‘*’ Operators Both the repetition operator (*) and the concatenation operator (+), can be used in a single expression to concatenate strings. The “*” operator has a higher precedence over the “+” operator. Example In the below example, we are concatenating strings using the + and * operator together. To form str3 string, Python concatenates 3 copies of World first, and then appends the result to Hello In the second case, the strings str1 and str2 are inside parentheses, hence their concatenation takes place first. Its result is then replicated three times. Apart from + and *, no other arithmetic operators can be used with string operands.
Modify Strings
String modification refers to the process of changing the characters of a string. If we talk about modifying a string in Python, what we are talking about is creating a new string that is a variation of the original one. In Python, a string (object of str class) is of immutable type. Here, immutable refers to an object that cannot be modified in place once it’s created in memory. Unlike a list, we cannot overwrite any character in the sequence, nor can we insert or append characters to it directly. If we need to modify a string, we will use certain string methods that return a new string object. However, the original string remains unchanged. We can use any of the following tricks as a workaround to modify a string. Converting a String to a List Both strings and lists in Python are sequence types, they are interconvertible. Thus, we can cast a string to a list, modify the list using methods like insert(), append(), or remove() and then convert the list back to a string to obtain a modified version. Suppose, we have a string variable s1 with WORD as its value and we are required to convert it into a list. For this operation, we can use the list() built-in function and insert a character L at index 3. Then, we can concatenate all the characters using join() method of str class. Example The below example practically illustrates how to convert a string into a list. Open Compiler It will produce the following output − Using the Array Module To modify a string, construct an array object using the Python standard library named array module. It will create an array of Unicode type from a string variable. Example In the below example, we are using array module to modify the specified string. Open Compiler It will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Using the StringIO Class Python’s io module defines the classes to handle streams. The StringIO class represents a text stream using an in-memory text buffer. A StringIO object obtained from a string behaves like a File object. Hence we can perform read/write operations on it. The getvalue() method of StringIO class returns a string. Example Let us use the above discussed principle in the following program to modify a string. Open Compiler It will produce the following output −