Access Tuple Items The most common way to access values within a Python tuple is using indexing, We just need to specify the index of the elements we want to retrieve to the square bracket [] notation. In Python, a tuple is an immutable ordered collection of elements. “Immutable” means that once a tuple is created, we cannot modify or change its contents. We can use tuples to group together related data elements, similar to lists, but with the key difference that tuples are immutable, while lists are mutable. In addition to indexing, Python provides various other ways to access tuple items such as slicing, negative indexing, extracting a subtuple from a tuple etc. Let us go through this one-by-one − Accessing Tuple Items with Indexing Each element in a tuple corresponds to an index. The index starts from 0 for the first element and increments by one for each subsequent element. Index of the last item in the tuple is always “length-1”, where “length” represents the total number of items in the tuple. To access the elements of a tuple we just need to specify the index of the item we need to access/retrieve, as shown below − tuple[3] Example Following is the basic example to access tuple items with slicing index − 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. Accessing Tuple Items with Negative Indexing Negative indexing in Python is used to access elements from the end of a tuple, with -1 referring to the last element, -2 to the second last, and so on. We can also access tuple items with negative indexing by using negative integers to represent positions from the end of the tuple. Example In the following example, we are accessing tuple items with negative indexing − Open Compiler We get the output as shown below − Accessing Range of Tuple Items with Negative Indexing By range of tuple items, we mean accessing a subset of elements from a tuple using slicing. Therefore, we can access a range of tuple items with negative indexing by using the slicing operation in Python. Example In the example below, we are accessing a range of tuple items by using negative indexing − Open Compiler It will produce the following output − Access Tuple Items with Slice Operator The slice operator in Python is used to fetch one or more items from the tuple. We can access tuple items with the slice operator by specifying the range of indices we want to extract. It uses the following syntax − Where, Example In the following example, we are retrieving subtuple from index 1 to last in “tuple1” and index 0 to 1 in “tuple2”, and retrieving all elements in “tuple3” − Open Compiler Following is the output of the above code − Accessing Sub Tuple from a Tuple A subtuple is a part of a tuple that consists of a consecutive sequence of elements from the original tuple. We can access a subtuple from a tuple by using the slice operator with appropriate start and stop indices. It uses the following syntax − 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 tuple. Example In this example, we are fetching subtuple from index “1 to 2” in “tuple1” and index “0 to 1” in “tuple2” using slice operator − Open Compiler The output obtained is as follows −
Tuples
Tuple is one of the built-in data types in Python. A Python tuple is a sequence of comma separated items, enclosed in parentheses (). The items in a Python tuple need not be of same data type. Following are some examples of Python tuples − The empty tuple is written as two parentheses containing nothing − tup1 =(); To write a tuple containing a single value you have to include a comma, even though there is only one value − tup1 =(50,); Following are the points to be noted − Accessing Values in Tuples To access values in tuple, 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 − Updating Tuples Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates − 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. Delete Tuple Elements Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. To explicitly remove an entire tuple, just use the del statement. For example − Open Compiler This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more − Python Tuple Operations In Python, Tuple is a sequence. Hence, we can concatenate two tuples with + operator and concatenate multiple copies of a tuple with “*” operator. The membership operators “in” and “not in” work with tuple 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 Even if there is only one object in a tuple, you must give a comma after it. Otherwise, it is treated as a string. Indexing, Slicing, and Matrixes Because tuples are sequences, indexing and slicing work the same way for tuples 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 No Enclosing Delimiters Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples − Open Compiler When the above code is executed, it produces the following result − Built-in Functions with Tuples Following are the built-in functions we can use with tuples − Sr.No. Function with Description 1 cmp(tuple1, tuple2)Compares elements of both tuples. 2 len(tuple)Gives the total length of the tuple. 3 max(tuple)Returns item from the tuple with max value. 4 min(tuple)Returns item from the tuple with min value. 5 tuple(seq)Converts a list into tuple.
List Exercises
Python List Exercise 1 Python program to find unique numbers in a given list. Open Compiler It will produce the following output − Python List Exercise 2 Python program to find sum of all numbers in a list. 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. Python List Exercise 3 Python program to create a list of 5 random integers. Open Compiler It will produce the following output −
List Methods
List is one of the fundamental data structures in Python, It provides a flexible way to store and manage a collection of items. It has several built-in methods that allow you to add, update, and delete items efficiently. Lists in Python can contain items of different data types, including other lists, making them highly flexible to different scenarios. The list object includes several built-in methods that allow you to add, update, and delete items efficiently, as well as to perform various operations on the list’s elements. Python List Methods The list methods enable you to manipulate lists easily and effectively, whether you are appending new items, removing existing ones, or even sorting and reversing the list. By using these built-in methods, you can work with lists in Python more effectively, allowing you to write more efficient and readable code. Printing All the List Methods To view all the available methods for lists, you can use the Python dir() function, which returns all the properties and functions related to an object. Additionally, you can use the Python help() function to get more detailed information about each method. For example: Open Compiler The above code snippet provides a complete list of properties and functions related to the list class. It also demonstrates how to access detailed documentation for a specific method in your Python environment. Here is the output − Below, the built-in methods for lists in Python, which are categorized based on their functionality. Let’s explore and understand the basic fuctionality of each method. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Methods to Add Elements to a List The following are the methods specifically designed for adding new item/items into a list − Sr.No. Methods with Description 1 list.append(obj)Appends object obj to list. 2 list.extend(seq)Appends the contents of seq to list 3 list.insert(index, obj)Inserts object obj into list at offset index Methods to Remove Elements from a List The following are the methods specifically designed for removing items from a list − Sr.No. Methods with Description 1 list.clear()Clears all the contents of the list. 2 list.pop(obj=list[-1])Removes and returns the last object or the object at the specified index from the list. 3 list.remove(obj)Removes the first occurrence of object obj from the list. Methods to Access Elements in a List These are the methods used for finding or counting items in a list − Sr.No. Methods with Description 1 list.index(obj)Returns the lowest index in list that obj appears 2 list.count(obj)Returns count of how many times obj occurs in the list. Copying and Ordering Methods These are the methods used for creating copies and arranging items in a list − Sr.No. Methods with Description 1 list.copy()Returns a copy of the list object. 2 list.sort([func])Sorts the objects in the list in place, using a comparison function if provided. 3 list.reverse()Reverses the order of objects in the list in place.
Join Lists
Join Lists in Python Joining lists in Python refers to combining the elements of multiple lists into a single list. This can be achieved using various methods, such as concatenation, list comprehension, or using built-in functions like extend() or + operator. Joining lists does not modify the original lists but creates a new list containing the combined elements. Join Lists Using Concatenation Operator The concatenation operator in Python, denoted by +, is used to join two sequences, such as strings, lists, or tuples, into a single sequence. When applied to lists, the concatenation operator joins the elements of the two (or more) lists to create a new list containing all the elements from both lists. We can join a list using the concatenation operator by simply using the + symbol to concatenate the lists. Example In the following example, we are concatenating the elements of two lists “L1” and “L2”, creating a new list “joined_list” containing all the elements from both lists − Open Compiler 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. Join Lists Using List Comprehension List comprehension is a concise way to create lists in Python. It is used to generate new lists by applying an expression to each item in an existing iterable, such as a list, tuple, or range. The syntax for list comprehension is − This creates a new list where expression is evaluated for each item in the iterable. We can join a list using list comprehension by iterating over multiple lists and appending their elements to a new list. Example In this example, we are joining two lists, L1 and L2, into a single list using list comprehension. The resulting list, joined_list, contains all elements from both L1 and L2 − Open Compiler Output of the above code is as follows − Join Lists Using append() Function The append() function in Python is used to add a single element to the end of a list. This function modifies the original list by adding the element to the end of the list. We can join a list using the append() function by iterating over the elements of one list and appending each element to another list. Example In the example below, we are appending elements from “list2” to “list1” using the append() function. We achieve this by iterating over “list2” and adding each element to “list1” − Open Compiler We get the output as shown below − Join Lists Using extend() Function The Python extend() function is used to append elements from an iterable (such as another list) to the end of the list. This function modifies the original list in place, adding the elements of the iterable to the end of the list. We can join a list using the extend() function by calling it on one list and passing another list (or any iterable) as an argument. This will append all the elements from the second list to the end of the first list. Example In the following example, we are extending “list1” by appending the elements of “list2” using the extend() function − Open Compiler The output obtained is as shown below −
Copy Lists
Copying a List in Python Copying a list in Python refers to creating a new list that contains the same elements as the original list. There are different methods for copying a list, including, using slice notation, the list() function, and using the copy() method. Each method behaves differently in terms of whether it creates a shallow copy or a deep copy. Let us discuss about all of these deeply in this tutorial. Shallow Copy on a Python List A shallow copy in Python creates a new object, but instead of copying the elements recursively, it copies only the references to the original elements. This means that the new object is a separate entity from the original one, but if the elements themselves are mutable, changes made to those elements in the new object will affect the original object as well. Example of Shallow Copy Let us illustrate this with the following example − Open Compiler As you can see, even though we only modified the first element of the first sublist in the shallow copied list, the same change is reflected in the original list as well. This is because a shallow copy only creates new references to the original objects, rather than creating copies of the objects themselves − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Deep Copy on a Python List A deep copy in Python creates a completely new object and recursively copies all the objects referenced by the original object. This means that even nested objects within the original object are duplicated, resulting in a fully independent copy where changes made to the copied object do not affect the original object, and vice versa. Example of Deep Copy Let us illustrate this with the following example − Open Compiler As you can see, when we modify the first element of the first sublist in the deep copied list, it does not affect the original list. This is because a deep copy creates a new object and recursively copies all the nested objects, ensuring that the copied object is fully independent from the original one − Copying List Using Slice Notation Slice notation in Python allows you to create a subsequence of elements from a sequence (like a list, tuple, or string) by specifying a start index, an end index, and an optional step size. The syntax for slice notation is as follows − [start:end:step] Where, start is the index where the slice starts, end is the index where the slice ends (exclusive), and step is the step size between elements. We can copy a list using slice notation by specifying the entire range of indices of the original list. This effectively creates a new list with the same elements as the original list. Any modifications made to the copied list will not affect the original list, and vice versa, because they are separate objects in memory. Example In this example, we are creating a slice of the “original_list”, effectively copying all its elements into a new list “copied_list” − Open Compiler We get the result as shown below − Copying List Using the list() Function The list() function in Python is a built-in function used to create a new list object. It can accept an iterable (like another list, tuple, set, etc.) as an argument and create a new list containing the elements of that iterable. If no argument is provided, an empty list is created. We can copy a list using the list() function by passing the original list as an argument. This will create a new list object containing the same elements as the original list. Example In the example below, we are creating a new list object “copied_list” containing the same elements as “original_list” using the list() function − Open Compiler Following is the output of the above code − Copying List Using the copy() Function In Python, the copy() function is used to create a shallow copy of a list or other mutable objects. This function is part of the copy module in Python’s standard library. We can copy a list using the copy() function by invoking it on the original list. This creates a new list object that contains the same elements as the original list. Example In the following example, we are using the copy() function to creates a new list object “copied_list” containing the same elements as “original_list” − Open Compiler Output of the above code is as shown below −
Sort Lists
Sorting Lists in Python Sorting a list in Python is a way to arrange the elements of the list in either ascending or descending order based on a defined criterion, such as numerical or lexicographical order. This can be achieved using the built-in sorted() function or by calling the sort() method on the list itself, both of which modify the original list or return a new sorted list depending on the method used. Sorting Lists Using sort() Method The python sort() method is used to sort the elements of a list in place. This means that it modifies the original list and does not return a new list. Syntax The syntax for using the sort() method is as follows − Where, Example of Sorting List in Lexicographical Order In the following example, we are using the sort() function to sort the items of the list alphanumerically − Open Compiler It will produce the following output − Example of Sorting List in Numerical Order In here, we are using the sort() function to sort the given list in numerical order − Open Compiler The output produced is as shown below − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Sorting Lists Using sorted() Method The sorted() function in Python is a built-in function used to sort the elements of an iterable (such as a list, tuple, or string) and returns a new sorted list, leaving the original iterable unchanged. Syntax The syntax for using the sorted() method is as follows − Where, Example In the following example, we are using the sorted() function to sort a list of numbers and retrieve a new sorted list − Open Compiler Following is the output of the above code − Sorting List Items with Callback Function In Python, a callback function refers to a function that is passed as an argument to another function and is invoked or called within that function We can sort list items with a callback function by using the sorted() function or sort() function in Python. Both of these functions allows us to specify a custom sorting criterion using the “key” parameter, which accepts a callback function. This callback function defines how the elements should be compared and sorted. Example Using str.lower() as key Parameter The str.lower() method in Python is used to convert all the characters in a string to lowercase. It returns a new string with all alphabetic characters converted to lowercase while leaving non-alphabetic characters unchanged. In this example, we are passing the str.lower() method as an argument to the “key” parameter within the sort() function − Open Compiler It will produce the following output − Example Using user-defined Function as key Parameter We can also use a user-defined function as the key parameter in sort() method. In this example, the myfunction() uses % operator to return the remainder, based on which the sorting is performed − Open Compiler It will produce the following output −
List Comprehension
List Comprehension in Python A list comprehension is a concise way to create lists. It is similar to set builder notation in mathematics. It is used to define a list based on an existing iterable object, such as a list, tuple, or string, and apply an expression to each element in the iterable. Syntax of Python List Comprehension The basic syntax of list comprehension is − Where, Example of Python List Comprehension Suppose we want to convert all the letters in the string “hello world” to their upper-case form. Using list comprehension, we iterate through each character, check if it is a letter, and if so, convert it to uppercase, resulting in a list of uppercase letters − Open Compiler The result obtained is displayed as follows − List Comprehensions and Lambda In Python, lambda is a keyword used to create anonymous functions. An anonymous function is a function defined without a name. These functions are created using the lambda keyword followed by a comma-separated list of arguments, followed by a colon :, and then the expression to be evaluated. We can use list comprehension with lambda by applying the lambda function to each element of an iterable within the comprehension, generating a new list. Example In the following example, we are using list comprehension with a lambda function to double each element in a given list “original_list”. We iterate over each element in the “original_list” and apply the lambda function to double it − Open Compiler 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. Nested Loops in Python List Comprehension A nested loop in Python is a loop inside another loop, where the inner loop is executed multiple times for each iteration of the outer loop. We can use nested loops in list comprehension by placing one loop inside another, allowing for concise creation of lists from multiple iterations. Example In this example, all combinations of items from two lists in the form of a tuple are added in a third list object − Open Compiler It will produce the following output − Conditionals in Python List Comprehension Conditionals in Python refer to the use of statements like “if”, “elif”, and “else” to control the flow of a code based on certain conditions. They allow you to execute different blocks of code depending on whether a condition evaluates to “True” or “False”. We can use conditionals in list comprehension by including them after the iterable and before the loop, which filters elements from the iterable based on the specified condition while generating the list. Example The following example uses conditionals within a list comprehension to generate a list of even numbers from 1 to 20 − Open Compiler We get the output as follows − List Comprehensions vs For Loop List comprehensions and for loops are both used for iteration, but they differ in terms of syntax and usage. List comprehensions are like shortcuts for creating lists in Python. They let you generate a new list by applying an operation to each item in an existing list. For loop, on the other hand, is a control flow statement used to iterate over elements of an iterable one by one, executing a block of code for each element. List comprehensions are often preferred for simpler operations, while for loops offer more flexibility for complex tasks. Example Using For Loop Suppose we want to separate each letter in a string and put all non-vowel letters in a list object. We can do it by a for loop as shown below − Open Compiler The chars list object is displayed as follows − Example Using List Comprehension We can easily get the same result by a list comprehension technique. A general usage of list comprehension is as follows − Applying this, chars list can be constructed by the following statement − Open Compiler The chars list will be displayed as before − Example The following example uses list comprehension to build a list of squares of numbers between 1 to 10 − Open Compiler The squares list object is − Advantages of List Comprehension Following are the advantages of using list comprehension −
Loop Lists
Loop Through List Items Looping through list items in Python refers to iterating over each element within a list. We do so to perform the desired operations on each item. These operations include list modification, conditional operations, string manipulation, data analysis, etc. Python provides various methods for looping through list items, with the most common being the for loop. We can also use the while loop to iterate through list items, although it requires additional handling of the loop control variable explicitly i.e. an index. Loop Through List Items with For Loop A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string, or range) or any other iterable object. It allows you to execute a block of code repeatedly for each item in the sequence. In a for loop, you can access each item in a sequence using a variable, allowing you to perform operations or logic based on that item’s value. We can loop through list items using for loop by iterating over each item in the list. Syntax Following is the basic syntax to loop through items in a list using a for loop in Python − Example In the following example, we are using a for loop to iterate through each element in the list “lst” and retrieving each element followed by a space on the same line − 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. Loop Through List Items with While Loop A while loop in Python is used to repeatedly execute a block of code as long as a specified condition evaluates to “True”. We can loop through list items using while loop by initializing an index variable, then iterating through the list using the index variable and incrementing it until reaching the end of the list. An index variable is used within a loop to keep track of the current position or index in a sequence, such as a list or array. It is generally initialized before the loop and updated within the loop to iterate over the sequence. Syntax Following is the basic syntax for looping through items in a list using a while loop in Python − Example In the below example, we iterate through each item in the list “my_list” using a while loop. We use an index variable “index” to access each item sequentially, incrementing it after each iteration to move to the next item − Open Compiler Output Output of the above code is as follows − Loop Through List Items with Index An index is a numeric value representing the position of an element within a sequence, such as a list, starting from 0 for the first element. We can loop through list items using index by iterating over a range of indices corresponding to the length of the list and accessing each element using the index within the loop. Example This example initializes a list “lst” with integers and creates a range of indices corresponding to the length of the list. Then, it iterates over each index in the range and prints the value at that index in the list “lst” − Open Compiler Output We get the output as shown below − Iterate using List Comprehension A list comprehension in Python is a concise way to create lists by applying an expression to each element of an iterable. These expressions can be arithmetic operations, function calls, conditional expressions etc. We can iterate using list comprehension by specifying the expression and the iterable (like a list, tuple, dictionary, string, or range). Following is the syntax − This applies the expression to each item in the iterable and creates a list of results. Example In this example, we use list comprehension to iterate through each number in a list of numbers, square each one, and store the squared result in the new list “squared_numbers” − Open Compiler Output We get the output as shown below − Iterate using the enumerate() Function The enumerate() function in Python is used to iterate over an iterable object while also providing the index of each element. We can iterate using the enumerate() function by applying it to the iterable. Following is the syntax − This provides both the index and item of each element in the iterable during iteration Example In the following example, we are using the enumerate() function to iterate through a list “fruits” and retrieve each fruit along with its corresponding index − Open Compiler Output We get the output as shown below −
Remove List Items
Removing List Items Removing list items in Python implies deleting elements from an existing list. Lists are ordered collections of items, and sometimes you need to remove certain elements from them based on specific criteria or indices. When we remove list items, we are reducing the size of the list or eliminating specific elements. We can remove list items in Python using various methods such as remove(), pop() and clear(). Additionally, we can use the del statement to remove items at a specific index. Let us explore through all these methods in this tutorial. Remove List Item Using remove() Method The remove() method in Python is used to remove the first occurrence of a specified item from a list. We can remove list items using the remove() method by specifying the value we want to remove within the parentheses, like my_list.remove(value), which deletes the first occurrence of value from my_list. Example In the following example, we are deleting the element “Physics” from the list “list1” using the remove() method − 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. Remove List Item Using pop() Method The pop() method in Python is used to removes and returns the last element from a list if no index is specified, or removes and returns the element at a specified index, altering the original list. We can remove list items using the pop() method by calling it without any arguments my_list.pop(), which removes and returns the last item from my_list, or by providing the index of the item we want to remove my_list.pop(index), which removes and returns the item at that index. Example The following example shows how you can use the pop() method to remove list items − Open Compiler We get the output as shown below − Remove List Item Using clear() Method The clear() method in Python is used to remove all elements from a list, leaving it empty. We can remove all list items using the clear() method by calling it on the list object like my_list.clear(), which empties my_list, leaving it with no elements. Example In this example, we are using the clear() method to remove all elements from the list “my_list” − Open Compiler Output of the above code is as follows − Remove List Item Using del Keyword The del keyword in Python is used to delete element either at a specific index or a slice of indices from memory. We can remove list items using the del keyword by specifying the index or slice of the items we want to delete, like del my_list[index] to delete a single item or del my_list[start:stop] to delete a range of items. Example In the below example, we are using the “del” keyword to delete an element at the index “2” from the list “list1” − Open Compiler The result produced is as follows − Example In here, we are deleting a series of consecutive items from a list with the slicing operator − Open Compiler It will produce the following output −