Lists and List Methods in Python

List in PythonLists 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 valuesThere 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.

Example:

name = [3,2,1,9,5]
print(name[3])

# output 
9
// Note: Indexing in list start from 0

 

list in python programming

How indexes are assigned to list elements?

list in python

List lengthTo 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.

Example:

name = [1,2,3,4,5]
print (len (name))

# output
5

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.

Example:

name = [1,2,3,4,5]
print(1 in name)

# output
True

 

list operations in python programming

Operations on List in Python

Operations on listThere 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.

Example 2:

list = [0] * 4
# output
[0,0,0,0]

1). List SlicesSlice 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']
# Example 2 
['a' , 'b' , 'c' , 'd'] 
print(list[3:]) 
# output ['d', 'e' , 'f']

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:

Example 2:

alphabets = ['a' , 'b' , 'c' , 'd' , 'e']
alphabets[1:3] = ['x','y']
print(alphabets)

# output
['a','x','y','d','e','f']

 

(iii). Removing elements: We can remove elements from a list by assigning an empty list to them.

Example:

test = ['a' , 'b' , 'c' , 'd' , 'e' , 'f']
test[1:3] = []
print(test)

# output['a','d','e','f']

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']
# Example 2 
test[4:4] = ['x'] 
print(test) 

# output 
['a','b','c','d','e','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

lists = ['a' , 'b' , 'c' , 'd' , 'e' , 'f']
del lists[1:5]
print(lists)

# output
['a','f']

5). List MembershipOperator ‘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

NoteIf elements exist in the list then the output is True else it returns False.


6). Lists and for loopsIf 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.

Example:

for number in range(20): 
    if number % 2 ==0:
        print number

What is range() function in python?

The above example print all the even numbers between the range zero and 19.


7). Length of ListIn 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 ValuesObject and values are one of the important concepts of any programming language to understand.

if we execute the below-given assignment statements,

a = “apple”
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.

list in python

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.

Example:

a = "apple"
b = "apple"
print(id(a))
print(id(b))

Note: Output varies it may be a sequence of number ie. 1324543 etc.

143657489
143657489

ImportantWe can see that we got the same identifier twice, it means that python created only one string and it makes referred both variable a and b to the same string.

But the interesting thing to know is, in case of lists, it behaves differently. We get two objects if we create two lists and more objects if we create more lists.

Example

a = [1,2,3]
b = [1,2,3]
print(id(a))
print(id(a))

Output:

342532
453456

We may assume our state diagram like this:

                                      a ——->  [1,2,3]
                                      b ——->  [1,2,3]

It shows that a & b may have same values but they are not referring to the same object.


9). Aliasing in ListAs 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:

operations on list in python

NoteWhat 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.

Example

a = [2,4,3]
b = a[:]
b[0] = 7
print(a)

# output
[2,4,3]

11). Nested ListsList 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]

Example

a = [1,2,3,[21,"www.pythonlobby.com"]]
print(a[1])
#output 
[21,'www.pythonlobby.com']

print(a[1][1])

#output
['www.pythonlobby.com']

 

matrices in python

12). Matrices in Python: Nested lists are mainly used to represent matrices in Python. For example, matrices look like this:

matrices in python

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.

Example

matrice = [[1,2,3],[4,5,6],[7,8,9]]
print(matrice[1])

# output
[4,5,6]

print(matrice[1][1])

# output
5

NoteIn matrices slicing, the first index selects the row, and second index selects the column. This is the common way to represent matrices.


13). Strings and ListsIn 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']

Example 2:

x = "Hello-there!-how-are-you" 
z = x.split("-") 
print(z) 

# output 
['Hello','there!','how','are','you']

 

operations on list

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.
  • IndexAn integer variable or value that are used to indicate elements of lists are called an index.
  • ElementsValues or variables or we can say data available in the list are called elements of a list.
  • Nested listA list having one or more sub-lists is called a nested list.
  • ObjectA referring variable that is referring to something is called an object.
  • AliasesMultiple variables that are referring to the same object.
  • CloneTo 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.

–> Programming exercises on List