Lists and List Methods in Python
List in Python: Lists in Python programming is a kind of data structures or it is an ordered set of values. Each value in the list identified by an index. Values stored by the list may be an integer, string or float etc. Values inside the list are called elements.
Elements can be of any types. It may be integers, strings etc. We can also perform various operations on list in python. It has many built-in list methods.
More about lists in detail
List values: There are several ways to create lists. The simplest way to create a list in python is to enclose the elements in square brackets [ ]
Syntax:
data = [] data = [1,2,3,"raj",1.0] print(data) # output [1,2,3,"raj",1.0]
Accessing elements of lists: The technique of accessing the elements of a list is called List Slicing. The syntax of accessing the elements of a list is the same as that of accessing the characters of a string in Python (using the [] operator). We pass the index of the element inside the square bracket.
How indexes are assigned to list elements?
List length: To find the length of a list or to check the length of elements of a list, we use the list in-built method len(). The len() method return the length of list. This is one of the powerful concepts used in a list. It makes very easy for solving puzzled problems without writing complex code.
List Membership: The membership operators are available in Python are in and not in. These operators are used to check the existence of membership in a sequence. If the value exists then it returns True as output else it returns False. Performing operation by using both list and membership operators together is called List Membership.
Operations on List in Python
Operations on list: There are many operations performed on list in Python. We will discuss it one by one with examples. Some common operations are using operators +,* etc.
Example:
a = [2,1,3] b = [1,2,3] z = a + b print(z) # output [2, 1, 3, 1, 2, 3]
The above given example is the common example on list operation using plus(+) operator. It joins the list. Similarly * operator repeats a list a given number of times.
1). List Slices: Slice operation in list are mainly used to access the elements of the list.
# Example 1 list = ['a' , 'b' , 'c' , 'd' , 'e' , 'f'] print(list[1:3]) # output ['b' , 'c']
2). List are Mutable: We know that strings are mutable. Mutable means we can change their values or elements. Let’s see an example to understand How we can change the values of List in python?
Example 1:
fruits = ["orange" , "banana" , "apple"] fruits[0] = ["grapes"] print(fruits) # output ['grapes','banana','apple']
(ii). Multiple Changes at Once: We can also update multiple elements of lists at once using the slice operator. Let’s see one example:
(iii). Removing elements: We can remove elements from a list by assigning an empty list to them.
3). Adding Elements: We can also add elements to a list by squeezing them into an empty slice, at the required location.
Example:
test = ['a' , 'd' , 'f'] test[1:1] = ['b' , 'c'] print(list) # output ['a','b','c','d','f']
4). List Deletion: We can also delete elements of a list if required. Python provides an alternative, that is more readable. del is used to remove an element from a list in python.
lists = ['apple' , 'banana' , 'oranges'] del lists[1] print(lists) # output ['apple','oranges']
We can also use the slices operator for multiple list elements deletion.
Example
5). List Membership: Operator ‘in’ is a boolean operator that is used to check membership or existence of elements in a list and return True or False as a result/output.
test = ["apple" , "banana" , "oranges" , "mangoes"] x = "apple" in test print(x) # output True
Note: If elements exist in the list then the output is True else it returns False.
6). Lists and for loops: If you don’t know about for loop then Please refer to this article for loop.
The for loop also works with lists. The common syntax to use for loop in python is:
for VARIABLE in LIST: BODY
Here for is the reserved keyword and also in ( in is membership operator)
For loop is used to iterate over the list of sequence. Suppose we have a list x = [‘x’,’y’,’z’] . Now if we use for loop on our list then it will iterate over all the elements of the list one by one. Please follow below given example.
x = ['a' , 'b' , 'c' , 'd'] for i in x: print(i) # output a b c d
It almost reads like normal English: ” We can say that “for ( every ) i in x, print ( the name of the ) i.”
We can use any list expression in a for loop.
7). Length of List: In python, there is a function that is len(). It is used to find the length of a list in python. Let’s see an example that how to use len() function.
x = [1,2,3,4] z = len(x) print(z) # output 4
8). Object and Values: Object and values are one of the important concepts of any programming language to understand.
if we execute the below-given assignment statements,
b = “apple”
It is clear that a and b are referring to a string with word “apple“. But we cannot say that they are referring to the exact same string.
There are two possible states.
If we carefully look at the above-given diagram. we will observe that there are two phases 1&2. In 1 phase, a and b refer to two different strings. But in the second phase, a and b refer to the same string. The “things” that have names — are called values. A variable or something that are referring to is called Objects.
Basically, every object has a unique identifier.
In python, an id() function is used to obtain the identifier. We can know the identifier of a & b and also we can tell whether they refer to the same object.
9). Aliasing in List: As we discussed above that variables may refer to objects, what if we assign one variable to another and that both values referring to the same object:
Let’s understand with the help of example
a = [3,2,1] b = a
In the above case, our state diagram/figure should look like this:
Note: What we did? we given two different names to the same list ie. a&b , now we can say that it is aliased. If we do any change in any of one list, then it may also affect the other list.
Example:
b[0] = 7 print(a) # output [7,2,1]
we did change in list b but it also affected list a.
10). List Cloning: List cloning is also a type of operation on list. Cloning means making a copy. Sometimes we need to copy a list and want to modify the copied list but do not want to make changes in the original list. In that case, we use the concept of cloning.
We use slice operator, the easiest way to clone a list:
Example:
x = [3,2,1] y = a[:] print(y) # output [3,2,1]
Now if we make any changes to y, it does not affect our original list. so now we are free to make any changes to our list.
11). Nested Lists: List or lists inside list is called nested list. Nested list looks like:
x = [1,2, [“www.pythonlobby.com”], 4,5]
In the above example, the second element is a nested list. If we print x[2], we get [‘www.pythonlobby.com’]. If we want to access elements inside the nested list, then in that case we need to proceed with two steps:
x[2][0]
12). Matrices in Python: Nested lists are mainly used to represent matrices in Python. For example, matrices look like this:
It might also be represented as z = [[1,2,3], [4,5,6],[7,8,9]] in python. In the case of matrices, the slicing of elements is a little bit different ie.
13). Strings and Lists: In this topic, we will learn some functions of string ie. split(). The split function is the string function. It is used to break a string and returns the result/output in list format.
Example 1:
x = "Hello there! how are you" z = x.split() print(z) # output ['Hello','there!','how','are','you']
Glossary:
- List: A list is a collection of ordered or unordered elements which can be accessed by indexing. It is also a type of linear data structure.
- Index: An integer variable or value that are used to indicate elements of lists are called an index.
- Elements: Values or variables or we can say data available in the list are called elements of a list.
- Nested list: A list having one or more sub-lists is called a nested list.
- Object: A referring variable that is referring to something is called an object.
- Aliases: Multiple variables that are referring to the same object.
- Clone: To create a new object similar or duplicate of another object. If we do any changes to any of the object, then it may not affect the other one.