Python Lists

Python Lists are sequential data types.

Python lists are enclosed with square brackets([]) and their elements are separated by comma(,).

Python Lists are mutable i.e. we can change any element(s) of lists if we want to change.

We can access list elements using the index value of the element.

Like strings, there is both side indexing in Python Lists i.e. from the front side, indexing starts with “0” and from the backside, indexing starts with “-1“.

Example

myList = [1, 2, 3, 4, "Hello", "World"]  # defining a list
print(myList)  # printing a list
print(myList[0])  # printing first element
print(myList[1])  # printing 2nd element
print(myList[5])  # printing last element
print(myList[-1])  # printing last element
print(myList[-2])  # printing last 2nd element

Output

[1, 2, 3, 4, 'Hello', 'World']
1
2
World
World
Hello

List Slicing

List Slicing is very easy, just type the range of indexes to get the elements inside that range.

Example

myList = [1, 2, 3, 4, "Hello", "World"]  # defining a list
print(myList)  # printing a list
print(myList[0:5])  # python automatically subtracts 
                                    # 2nd value with 1
print(myList[0:6])  # 6-1 = 5
print(myList[1:4])  # 4-1 = 3
print(myList[-4:-1])  # -1-1 = -2
print(myList[-3:-2])  # -2-1 = -3
print(myList[:6])  # python automatically assigns 0 
                       # if we don't put some value
print(myList[0:])  # python automatically assigns length
                   # of list if we don't put some value

Output

[1, 2, 3, 4, 'Hello', 'World']
[1, 2, 3, 4, 'Hello']
[1, 2, 3, 4, 'Hello', 'World']
[2, 3, 4]
[3, 4, 'Hello']
[4]
[1, 2, 3, 4, 'Hello', 'World']
[1, 2, 3, 4, 'Hello', 'World']

Changing Element Value

To change the element of the list, type the list name with the index in square brackets([]), and assign a different value like assigning a value to the variable.

Example

myList = [1, 2, 3, 4, "Hello", "World"]  # defining a list
print("List before change is-->", myList)
myList[0] = 0 # assigning different values
myList[1] = 1
myList[-1] = "Answer"
myList[-2] = "Question"
print("List after change is-->", myList)

Output

List before change is--> [1, 2, 3, 4, 'Hello', 'World']
List after change is--> [0, 1, 3, 4, 'Question', 'Answer']

List Methods/Functions

There are built-in List methods/functions provided by Python which you can use.

MethodUse
len()returns list length
sort()sorts the list
min()returns the minimum value from list
max()returns the maximum value from list
list()converts a sequential data type to list
append()adds an element at the end of the list
clear()removes all elements from the list
copy()returns the copied list
reverse()reverses the order of the elements of the list
sum()returns the sum of the elements of the list
range()returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number
pop()removes the element at the specified position
remove()removes the item with the specified value
index()returns the index of the first element with the specified value
insert()Adds an element at the specified position

The len() function

Using len() function, we can find the length of a list i.e. the number of elements present in the list.

Example

myList = [34, 12, 10, 50, 45, 13]
print(len(myList))

Output

6

The sort() method

Using the sort() method, we can sort any list but the elements in the list should be of the same datatypes like int or string.

Example

myList = [34, 12, 10, 50, 45, 13]
myList.sort()
print(myList)
myList2 = ["d", "c", "a", "b", "B", "A"]
myList2.sort()
print(myList2)

Output

[10, 12, 13, 34, 45, 50]
['A', 'B', 'a', 'b', 'c', 'd']

The min() method

Using the min() method, we can find the minimum value from the list but the elements in the list should be of the same datatypes like int or string.

Example

myList = [34, 12, 10, 50, 45, 13]
print(min(myList))
myList1 = ["d", "c", "a", "b", "B", "A"]
print(min(myList1))

Output

10
A

The max() method

Using the max() method, we can find the maximum value from the list but the elements in the list should be of the same datatypes like int or string.

Example

myList = [34, 12, 10, 50, 45, 13]
print(max(myList))
myList1 = ["d", "c", "a", "b", "B", "A"]
print(max(myList1))

Output

50
d

The list() method

Using the list() method, we can convert any sequence datatype into lists. Datatypes like Tuples, Strings, Sets, etc can be converted to Python Lists.

Example

myTuple = (1, 2, 3, 4)
myList1 = list(myTuple)
myString = "Hello"
myList2 = list(myString)
mySet = {1, 2, 3, 4}
myList3 = list(mySet)
print(myList1)
print(myList2)
print(myList3)

Output

[1, 2, 3, 4]
['H', 'e', 'l', 'l', 'o']
[1, 2, 3, 4]

The append() method

Using the append() method, we can add an element at the end of a Python List.

Example

myList = [1, 2, 3, 4]
myList.append(5)
print(myList)

Output

[1, 2, 3, 4, 5]

The clear() method

Using the clear() method, we can clear all elements from a Python List i.e. we can delete all elements.

Example

myList = [1, 2, 3, 4]
myList.clear()
print(myList)

Output

[]

The copy() method

Using the copy() method, we can copy one Python list to another Python list.

Example

myList1 = [1, 2, 3, 4]
myList2 = myList1.copy()
print(myList2)

Output

[1, 2, 3, 4]

Note:- You can not copy a list just by using the “=” operator as it will be called as assigning one list to another not copying. If you do that, then any changes you will make in the first list will also apply to the second list.

Example

myList1 = [1, 2, 3, 4]
myList2 = myList1  # referring one list to another
print(myList1)
print(myList2)
myList1.append(5)  # appending 5 in myList1
print(myList1)
print(myList2)  # changes will appear in myList2 too

Output

[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

The reverse() method

Using the reverse() method, we can reverse the order of the position of elements in a Python List.

Example

myList = [1, 2, 3, 4]
myList.reverse()
print(myList)

Output

[4, 3, 2, 1]

The sum() function

Using the sum() function, we can get the sum of Python’s iterable objects like Lists, Tuple, and dictionary. It takes two arguments, the first one is the iterable object and the second one is the number you want to add with the numbers present in the iterable object. The sum() function adds only numbers else it will give an error.

Example

myList = [1, 2, 3, 4, 5, 6, 7]
addition1 = sum(myList)
print(addition1)
addition2 = sum(myList, 3)
print(addition2)

Output

28
31

The range() function

Using the range() function, we can get a list that contains a sequence of numbers, starting from 0 by default, increments by 1 (by default), and stops before the specified number, since using the range() function we can create a list of the desired sequence which will save our time and work.

Example

myList1 = [range(15)]
myList2 = [range(4, 15)]
myList3 = [range(4, 15, 3)]
print(myList1)
print(myList2)
print(myList3)

Output

[range(0, 15)]
[range(4, 15)]
[range(4, 15, 3)]

Surprised, yes this is not what we wanted, actually, we need to unpack the result of the range() function using the argument-unpacking operator i.e. *.

Example

myList1 = [*range(15)]
myList2 = [*range(4, 15)]
myList3 = [*range(4, 15, 3)]
print(myList1)
print(myList2)
print(myList3)

Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 7, 10, 13]

The pop() function

Using the pop() function, we can remove the last value of the list. If we want to remove any other value from the list using the pop() function, then we need to pass the index number to the pop() function, or else the last value will be removed. The pop() function always returns the removed value.

Example

myList = [4, 5, 6, 7, 8, 9, 10, 11] 
print(myList.pop())  # 11
print(myList)
print(myList.pop(3))  # 7
print(myList)
print(myList.pop(0))  # 4
print(myList)
print(myList.pop())  # 10
print(myList)

Output

11
[4, 5, 6, 7, 8, 9, 10]
7
[4, 5, 6, 8, 9, 10]
4
[5, 6, 8, 9, 10]
10
[5, 6, 8, 9]

The remove() function

Using the remove() function, we can remove any element from the list. To remove an element, pass the element as an argument to the function. The remove() function does not return any value and gives an error if the value is not present in the list.

Example

myList = [4, 5, 6, 7, 8, 9, 10, 11]
print(myList.remove(4))  # removes 4 and returns nothing
print(myList)
myList.remove(7)
print(myList)
myList.remove(11)
print(myList)
print(myList.remove(3))  # 3 not present

Output

None
[5, 6, 7, 8, 9, 10, 11]
[5, 6, 8, 9, 10, 11]
[5, 6, 8, 9, 10]
Traceback (most recent call last):
  File "main.py", line 8, in 
    print(myList.remove(3))  # 3 not present
ValueError: list.remove(x): x not in list

What if one value is repeated? In that case, the remove() function removes the first one only and leaves other values at the same place where they were before.

Example

myList = [4, 5, 6, 7, 4, 8, 9, 4, 10, 11]
myList.remove(4)
print(myList)

Output

[5, 6, 7, 4, 8, 9, 4, 10, 11]

Now, let’s see a one-liner to remove all the similar elements from the list.

Example

myList = [4, 5, 6, 7, 4, 8, 9, 4, 10, 11]
while 4 in myList: myList.remove(4)
print(myList)

Output

[5, 6, 7, 8, 9, 10, 11]

The index() function

Using the index() function, we can find/search for an element in any list. As soon as the element is found, it returns the index of the element. If there are two or more elements with similar values in the list, it will return the index of the element with the lowest index number.

We can pass two more arguments to the index() function, start(from where we want to start searching the element in the list), and end(where we want to end searching the element in the list). These two arguments are optional.

Syntax:

listname.index(element, start, end)

Now, let’s see an example

Example

myList = [4, 5, 6, 7, 4, 8, 9]
print(myList.index(5))
print(myList.index(4))
print(myList.index(4, 2, 5))
print(myList.index(4, 2, 3))

Output

1
0
4
Traceback (most recent call last):
  File "main.py", line 5, in 
    print(myList.index(4, 2, 3))
ValueError: 4 is not in list

The insert() function

Using the insert() function, we can insert an element in the list on our desired location/index.

Syntax:

listname.insert(index, element)

If the index value is greater than or equal to the len(listname), then the element is inserted at the end of the list. It does not return any value and gives an error if it is used with other objects instead of the list.

Example

myList = [4, 5, 6, 7, 4, 8, 9]
myList.insert(0, 1)
print(myList)
myList.insert(1, 2)
print(myList)
myList.insert(10, 12)
print(myList)

Output

[1, 4, 5, 6, 7, 4, 8, 9]
[1, 2, 4, 5, 6, 7, 4, 8, 9]
[1, 2, 4, 5, 6, 7, 4, 8, 9, 12]

Also read:

  • YouTube Video Downloader Using Python
    This is just a two-line program but to convert it to GUI YouTube Video Downloader is a bit longer still, this program…
  • Yield Keyword in Python
    In this tutorial, we are going to learn about the Yield keyword in Python. It works like a return statement we used…
  • Write Happy Halloween in Python Turtle
    Introduction Hello, in this article we will see how to Write Happy Halloween in Python Turtle which is a library of python….
  • Word Mix in Python
    Problem Statement: We are given a sentence, we need to word mix in Python means we need to mix the words of…
  • Word counter in Java
    Hello friends, in this article, we will learn how to create a word counter in Java. Word counter in java can be…