Table of contents |
|
Introduction to Lists |
|
List Operations |
|
Traversing a List |
|
List Methods and Built-In Functions |
|
Nested Lists |
|
Copying Lists |
|
List as argument to a Function |
|
List Manipulation |
|
In Python, a list is a fundamental data type that represents an ordered collection of elements. What sets lists apart is their mutability, meaning you can change, add, or remove elements after the list has been created. Unlike strings, which are made up of characters, lists can contain elements of different data types, including integers, floats, strings, tuples, or even other lists.
Lists are particularly useful for grouping together items of mixed data types. For example, you could have a list that contains an integer, a string, and a float all in one.
Example:
Python provides a built-in data type called list to store a collection of data. A list is a mutable data type that is ordered and allows duplicate elements.
list1 is a list in Python that contains six even numbers. The numbers in the list are 2, 4, 6, 8, 10, and 12. When we print list1, we see the output as [2, 4, 6, 8, 10, 12].
list2 is a list in Python that contains the vowels 'a', 'e', 'i', 'o', and 'u'. When we print list2, we see the output as ['a', 'e', 'i', 'o', 'u'].
list3 is a list in Python that contains mixed data types, including an integer 100, a float 23.5, and a string 'Hello'. When we print list3, we see the output as [100, 23.5, 'Hello'].
list4 is a nested list in Python that contains three sublists, each representing a subject and its corresponding code. The sublists are ['Physics', 101], ['Chemistry', 202], and ['Maths', 303]. When we print list4, we see the output as [['Physics', 101], ['Chemistry', 202], ['Maths', 303]].
The elements present in a list can be accessed in the same manner as characters are accessed in a string.
For example, if we have a list called list1 , we can access its elements using their index positions, just like we would with a string.
In Python, lists are mutable, meaning their contents can be changed after the list has been created.
For example:
Lists in Python can be manipulated in various ways after they are created.
You can join two or more lists using the concatenation operator +.
Example:
Example with Color Lists:
Important Notes:
In Python, you can replicate a list using the repetition operator, which is represented by the symbol *.
For example:
Membership operators in Python, such as in and not in, are used to check whether an element is present in a list. These operators return True or False based on the presence of the element.
Slicing is a technique that can be used on both strings and lists to extract specific portions of the data.
For example, consider the list:
We can access each element of a list or traverse through a list using either a for loop or a while loop.
(A) List Traversal Using for Loop
Example 1: Using a for loop to print each item in the list
Code:
Output:
Red
Green
Blue
Yellow
Black
Example 2: Accessing elements using range() and len() functions
Code:
Red
Green
Blue
Yellow
Black
(B) List Traversal Using while Loop
Code:
Red
Green
Blue
Yellow
Black
Lists in Python come with a variety of built-in methods that are quite handy for programming tasks.
Description
A nested list is when a list is included as an element within another list.
Example
Let's say we have a list called list1 that contains various elements, including another list as one of its elements:
list1 = [1, 2, 'a', 'c', [6, 7, 8], 4, 9]
In this example, the fifth element of list1 is also a list: [6, 7, 8] . When we access this element with list1[4] , we get the nested list.
To access elements within the nested list, we need to specify two indices: list1[i][j]. Here, i indicates the index of the nested list within the main list, and j indicates the index of the element within the nested list.
For example, if we want to access the second element of the nested list in list1, we can use:
list1[4][1]
This means:
When you have a list in Python and you want to make a copy of it, simply assigning it to another list will not work as expected. For example:
list1 = [1, 2, 3] list2 = list1
In this case, list2 does not create a new list. Instead, it makes list1 and list2 refer to the same list object in memory. This means that list2 becomes an alias for list1, and any changes made to either list will affect the other.
For instance:
list1 will now be [1, 2, 3, 10] list2 will also reflect this change.
To create a copy of the list as a distinct object, you can use one of the following methods:
You can create a copy of a list by slicing it. This involves taking the entire list and storing it in a new variable. For example:
newList = oldList[:]
Example
>>> list1 = [1, 2, 3, 4, 5]
Output
>>> list2 = list1[:] >>> list2 [1, 2, 3, 4, 5]
Method 2: Using the list() Function
Another way to copy a list is by using the built-in list() function. This function takes an iterable and returns a new list. For instance:
newList = list(oldList)
Example
>>> list2 = list(list1)
Output
[10, 20, 30, 40]
You can also use the copy() function from the copy library to create a copy of a list. First, you need to import the copy library and then use its copy() function. For example:
import copy newList = copy.copy(oldList)
Example:
>>> import copy
>>> list1 = [1,2,3,4,5]
>>> list2 = copy.copy(list1)
>>> list2 [1, 2, 3, 4, 5]
When a list is passed as an argument to a function in Python, there are two important scenarios to consider:
(A) Modifying the Original List
In this scenario, changes made to the list inside the function are reflected in the original list outside the function. This happens because when a list is passed as an argument, a reference to the list is passed, not a copy.
For example, consider the following program where a list of numbers, list1, is passed to a function called increment(). This function increases each element of the list by 5.
Program: Program to increment the elements of a list. The list is passed as an argument to a function.
# Function to increment the elements of the list passed as argument
def increment(list2):
for i in range(0, len(list2)):
list2[i] += 5
print('Reference of list Inside Function', id(list2))
# End of function
list1 = [10, 20, 30, 40, 50] # Create a list
print("Reference of list in Main", id(list1))
print("The list before the function call")
print(list1)
increment(list1) # list1 is passed as parameter to function
print("The list after the function call")
print(list1)Output:
- Reference of list in Main: 70615968
- Reference of list Inside Function: 70615968 (The ID remains the same)
- The list after the function call: [15, 25, 35, 45, 55]
This example demonstrates that when a list is passed as an argument, any modifications made to it inside the function are reflected in the original list.
(B) Assigning a New Value to the List Inside the Function
If the list is assigned a new value inside the function, a new list object is created, and it becomes a local copy within the function. Changes made to this local copy do not affect the original list in the calling function.
For instance, consider the following program:
Program: Program to increment the elements of the list passed as parameter.
# Function to increment the elements of the list passed as argument
def increment(list2):
print("\nID of list inside function before assignment:", id(list2))
list2 = [15, 25, 35, 45, 55] # Assigning a new list to list2
print("ID of list changes inside function after assignment:", id(list2))
print("The list inside the function after assignment is:")
print(list2)
list1 = [10, 20, 30, 40, 50] # Create a list
print("ID of list before function call:", id(list1))
print("The list before function call:")
print(list1)
increment(list1) # list1 passed as parameter to function
print('\nID of list after function call:', id(list1))
print("The list after the function call:")
print(list1)Output:
- ID of list before function call: 65565640
- ID of list inside function before assignment: 65565640
- ID of list changes inside function after assignment: 65565600
- ID of list after function call: 65565640
In this chapter, we have learned how to create a list and the different ways to manipulate lists. In the following programs, we will apply various list manipulation methods.
Program: Write a user-defined function to check if a number is present in the list or not. If the number is present, return the position of the number. Print an appropriate message if the number is not present in the list.
Output:
How many numbers do you want to enter in the list: 5
Enter a list of numbers: 23
567
12
89
324
Enter the number to be searched:12
Number 12 is present at 3 position
33 docs|11 tests
|
1. What are the basic operations that can be performed on a list in Python? | ![]() |
2. How can I traverse a list in Python? | ![]() |
3. What are some common list methods and built-in functions in Python? | ![]() |
4. What is a nested list, and how do I access its elements? | ![]() |
5. How can I copy a list in Python, and what are the differences between shallow and deep copies? | ![]() |