πΈList
Python offers several built-in data structures to hold and manipulate data efficiently. One such data structure is a list, which is a collection of items stored in a specific order. A list is mutable, which means it can be changed after it is created.
In Python, lists are created by enclosing a comma-separated sequence of items in square brackets ([]), as shown below:
In this example, the list contains three integers and three strings. The order of the items in the list is preserved.
Lists are very versatile and can hold any type of data, including other lists. They also support various operations, such as indexing, slicing, adding, removing, and sorting elements.
In this section, we will discuss the properties and operations of Python lists in more detail.
Create a Python List
To create a Python list, you can use square brackets []
and separate the values with commas. Here is an example:
This creates a list with integers 1
, 2
, and 3
, as well as the strings "apple"
and "banana"
. You can also create an empty list like this:
Or create a list with a single value:
Access Python List Elements
To access the elements of a Python list, you can use the indexing operator []
. The index of the first element in a list is 0
, the second element has an index of 1
, and so on. You can also use negative indices to access elements from the end of the list, with -1
being the index of the last element, -2
being the index of the second last element, and so on.
Here's an example:
You can also use slicing to access a range of elements in a list. Slicing is done using the colon :
operator. The first number before the colon represents the starting index (inclusive), and the second number after the colon represents the ending index (exclusive).
If you omit the first number, Python assumes that you want to start at the beginning of the list. Similarly, if you omit the second number, Python assumes that you want to go until the end of the list.
You can also use negative indices when slicing. In that case, -1
represents the last element, -2
represents the second last element, and so on.
Negative Indexing in Python
Negative indexing in Python allows you to access elements of a list by counting from the end of the list. In other words, the index -1 refers to the last element, -2 refers to the second to last element, and so on.
For example, suppose we have a list my_list = [10, 20, 30, 40, 50]
. To access the last element of the list, we can use negative indexing like this:
This would assign the value 50
to the variable last_element
. Similarly, we can access the second to last element using -2
:
This would assign the value 40
to the variable second_to_last
.
Slicing of a Python List
Slicing is a technique used in Python to extract a portion of a list by specifying a range of indices. It returns a new list that contains the specified elements.
To slice a Python list, we use the slicing operator :
. The syntax for slicing a list is as follows:
start
: The starting index of the slice. If not specified, it defaults to 0.end
: The ending index of the slice. If not specified, it defaults to the length of the list.step
: The step size of the slice. If not specified, it defaults to 1.
Here are some examples of slicing a Python list:
Add Elements to a Python List
Python List provides different methods to add items to a list.
a. Using append()
The append()
method is used to add a single element to the end of an existing list.
Here's an example:
In this example, we first create a list my_list
with elements 1, 2, 3, and 4. We then call the append()
method on this list and pass it the argument 5. The append()
method adds 5 to the end of the list, and the final output is [1, 2, 3, 4, 5].
b. Using extend()
To add multiple elements to a Python list, you can use the extend()
method. This method takes an iterable as an argument and adds each element of the iterable to the end of the list.
Here's an example:
In this example, the extend()
method is used to add three elements to the end of the my_list
list. The argument passed to extend()
is a list [4, 5, 6]
, which is iterated over and each element is added to the end of the list.
You can also use other iterable objects such as tuples, sets, or even another list with the extend()
method.
Change List Items
To change items of a Python list, you can use the indexing and assignment operator =
to assign a new value to the desired element of the list.
Here's an example:
Output:
In the above example, we first created a list of fruits. Then, we used the indexing and assignment operator =
to change the second element of the list from banana
to kiwi
. Finally, we printed the modified list using the print()
function.
Remove an Item From a List
1. Using del()
In Python we can use the del statement to remove one or more items from a list. For example,
Output:
In the example above, we first create a list of fruits. Then, using the del
keyword, we delete the second element (index 1), which is 'banana'. Finally, we print the updated list to verify that the element has been deleted.
2. Using remove()
The remove()
method is used to remove the first occurrence of a specified value from a list.
Syntax: list_name.remove(value)
Example:
Output:
Python List Methods
Python List Methods are built-in functions that allow us to perform operations on Python lists. Some commonly used Python List Methods are:
append(): adds an element to the end of the list.
extend(): adds elements from an iterable to the end of the list.
insert(): adds an element at the specified index.
remove(): removes the first occurrence of the specified element from the list.
pop(): removes the element at the specified index, or the last element if no index is specified, and returns it.
clear(): removes all the elements from the list.
index(): returns the index of the first occurrence of the specified element.
count(): returns the number of times the specified element occurs in the list.
sort(): sorts the list in ascending order.
reverse(): reverses the order of the elements in the list.
These methods help us manipulate the list in various ways and make it more convenient to use.
Operation on List
To perform operations on a Python list, you can use a combination of built-in functions and methods. Some common operations on a Python list include:
Concatenation: You can concatenate two or more lists using the
+
operator or theextend()
method.Repetition: You can repeat a list a specified number of times using the
*
operator.Membership testing: You can test whether an element is present in a list using the
in
keyword.Length: You can get the length of a list using the
len()
function.Sorting: You can sort a list using the
sort()
method.Reversing: You can reverse a list using the
reverse()
method.Copying: You can create a copy of a list using the
copy()
method or thelist()
constructor.
Here are some examples:
Concatenation:
Repetition:
Membership testing:
Length:
Reversing:
Sorting:
Copying:
Function on List
To perform a function on a Python list, you can use various built-in functions provided by Python.
Here are some commonly used functions on a Python list:
len()
: This function returns the number of elements in the list.max()
: This function returns the largest element in the list.min()
: This function returns the smallest element in the list.sum()
: This function returns the sum of all elements in the list.sorted()
: This function returns a sorted list.reversed()
: This function returns a reversed list.any()
: This function returnsTrue
if at least one element in the list isTrue
, otherwise it returnsFalse
.all()
: This function returnsTrue
if all elements in the list areTrue
, otherwise it returnsFalse
.enumerate()
: This function returns an iterator of tuples containing the index and the value of each element in the list.zip()
: This function returns an iterator of tuples where each tuple contains the elements from the input lists at that index.filter()
: This function returns a new list containing only the elements for which the given function returnsTrue
.map()
: This function applies the given function to each element in the list and returns a new list containing the results.reduce()
: This function applies the given function to the first two elements in the list, then applies the function to the result and the next element in the list, and so on, until all elements have been processed. The final result is returned. Note thatreduce()
is not a built-in function in Python 3, but is available in thefunctools
module.
To perform a function on a Python list, you can use various built-in functions provided by Python. Here are some examples:
len()
: This function returns the length of the list, i.e., the number of elements in the list.
Example:
Output:
sum()
: This function returns the sum of all elements in the list.
Example:
Output:
max()
: This function returns the maximum value from the list.
Example:
Output:
min()
: This function returns the minimum value from the list.
Example:
Output:
sorted()
: This function returns a new sorted list.
Example:
Output:
reversed()
: This function returns a new reversed list.
Example:
Output:
Last updated