[Complete Tutorial] Python List with Programming Examples for Beginners

[Complete Tutorial] Python List with Programming Examples for Beginners

Do you want to learn Python List? How to create a list? How to add, update, and remove elements from the Python list?

This is a complete Python list tutorial for you.

You will learn the different syntaxes for performing different operations on the Python list. You will also learn the different list methods and built-in-functions you can use with Python list?

Even if you are beginners, I believe, going through this tutorial will lay the stone for mastering your Python skills. You can also bookmark this tutorial, so you can easily go through any of the syntaxes.

Let’s begin…

What is a List?

In Python programming, the list is the data structure that stores a set of elements. This means you can save multiple elements in a single list.

Python List Syntax:

Each element in the array should be separated by a comma (,). Enclose complete list in opening and closing square bracket “[]”.

You can store any valid data type elements in the list.

Example: [‘Alice’, ‘Employee’, ‘Developer’]

Here, all the elements in the list are string data types.

It is not necessary the data type of all the elements in the list should be the same.

Example: [‘Alice’, 26, ‘Developer’]

The above example is also a valid list. The first and third elements are strings. The second element is an integer.

Characteristics of Python List

Some of the characteristic of Python list:

  • The list can save heterogeneous data (data of different types). For example, you can save integer, float, and string data type elements into a single list.
  • Element in the list has a defined order.
  • The list can have duplicate elements, so the single element can be present at multiple places in the list.
  • Every element in the list has an index. And the index of the element starts with zero.
  • The list also has negative indexing. It means you can access the last element of the list by its index -1. The index of the second last element is -2. And so on…
  • The list is a mutable data type in Python. You can change the list after creating it.
  • The list can store another list as its element, it is called a nested list. I will explain this in the latter part of this tutorial.

It is similar to the array in other programming languages.

Where can a list be useful?

  • The list is a useful data structure when it needs to preserve the sequence of elements and iterate them later.
  • The list is very useful in Python to implement other data structures like queue and stack.

Different Python List Operations

Let’s see the practical Python list tutorial.

How to Create a List in Python?

It is pretty easy. You have to add elements in the square bracket. And you don’t require any built-in-function to create Python list.

#creating empty list

listObj = []

#create  list of integers

listObj = [1, 2, 3]

#creating list with mixed data types (heterogeneous list)

listObj = [1, "Hello", 3.4]

After creating a list, you can check the data type of the variable “listObj”

type(myList)

All the elements in the list are ordered and indexed. The first element will be indexed by zero, the second element will be indexed by one, and so on…

The index value will be used for accessing an element in the list.

How to Access Elements from a List?

You can print the complete list, just by its name.

listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k']
print(listObj)

To access any specific element in the list, you have to provide an index of the element in the list.

listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k'] 

print(listObj[1]) 
# Output: s

Negative Indexing in Python List.

Suppose you have a huge number of elements in the list and you want to access the element which resides at the end of the list.

It is very difficult to count the indices of the elements residing at the end of the list.

Python has negative indexing for you.

The index of the last element is -1. The index of the second last element is -2 and so on…

listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k'] 

print(listObj [-1]) 
# Output: k 

print(listObj [-3]) 
# Output: a

Even for the accessing last element, you don’t need to count the index of it. This makes your job pretty easy. And Python is known for its simplicity.

How to Slice Python List?

If you are not interested in the complete list, you can slice the Python list using indices.

Syntax:

list[start_index: end_index]

Example:

listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k'] 

# elements 3rd to 5th index
print(listObj [2:5]) 
#output: ['e', 's', 't']

Here you are slicing the list with the start index 2 and end index 5.  It prints the element at index 2, 3, and 4. The value of end_index is not inclusive, so the element at index 5 is not printed.

How to Access the First Four Elements in the List?

By default, if you don’t mention the start_index, the value of start_index is zero.

print(listObj [:4]) 
#['c' 's', 'e',  's']

How to Access All Elements from the List Starting from the 4th Element?

By default, if you don’t mention the end_index, the value of end_index is the same as the index of the last element.

print(listObj [3:]) 
#['s', 't', 'a', 'c', 'k']

If you don’t mention the start and end index, you will get a complete Python list.

print(listObj [:])

Practically it does not make sense.

Note: You can also use the negative indexing for slicing the list.

List Membership Test:

How to find if the given element is present in the list or not?

List membership test is the test to identify if the given element is present in the list or not. If it is present, return true. Otherwise, return false.

listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k'] 

print('t' in listObj ) 
#True 

print('z' in listObj ) 
#False

This is a very useful Python trick in many cases where you have to choose the operations based on the presence of an element in the list.

How to Update or Change the Value inside the Python List?

Suppose you are maintaining the list of all the even numbers. And you found a mistake in your list. Instead of all even numbers, there is an odd number in your list.

How you can update the wrong element?

even_list = [2, 3, 6, 8] 

# change the value of the 2nd element in the list. 
even_list [1] = 4 

print(even_list ) 
#[2, 4, 6, 8]

You can also use the slice syntax for changing more than one value in the list.

even_list = [2, 4, 6, 8] 

# change 2nd to 4th items 
even_list [1:4] = [10, 12, 14] 

print(even_list ) 
#[2, 10, 12, 14]

How to Add New Elements in the List?

There are multiple methods and ways of adding new elements to the existing Python list.

Use the append() method for adding a single element.

How to Add all the Elements from Another List?

Use the extend() method to add elements from another list to the existing list.

odd = [1, 3, 5] 

odd.append(7) 

print(odd) 
# Output: [1, 3, 5, 7] 

odd.extend([9, 11, 13]) 
print(odd) 
# Output: [1, 3, 5, 7, 9, 11, 13]

How to Add an Element in the List at a Particular Location/Index?

We learn earlier, list preserves the ordering and every element in the list has an index.

Use the insert() method for adding a new element at a specific location in the list.

The first parameter to the insert() method will be an index where you want to add a new element. And the second parameter is the actual element you want to add.

odd = [1, 9] 

odd.insert(1,3) 

print(odd) 
# Output: [1, 3, 9]

Note: If you provide the index out of range, it will add an element at the end of the list.

Using Indexing:

You can also use the below syntax rather than using the insert() method.

odd = [1, 3, 9] 

odd[2]=5 

print(odd) 
# Output: [1, 3, 5, 9]

Note: Unline earlier, if you give the index out of range, your program will throw an error.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

Using Slice Indices:

odd=[1, 3, 9] 

odd[2:2] = [5, 7] 

print(odd) 
# Output: [1, 3, 5, 7, 9]

Hope you find the difference between append(), extend() and insert() method for adding elements in the list.

How to Delete or Remove Elements from a List?

The “del” is the new keyword you have to use.

Use the index for removing a single element from the list.

To delete multiple elements in the lust, use the slice indexing mechanism.

You can also delete the entire list.

my_list = ['p','r','o','b','l','e','m'] 

# delete one item 
del my_list[2] 
print(my_list) 
# Output: ['p', 'r', 'b', 'l', 'e', 'm'] 

# delete multiple items 
del my_list[1:5] 
print(my_list) 
# Output: ['p', 'm'] 

# delete entire list 
del my_list 
print(my_list) 
# Error: List not defined

How to Remove Element if You Know the Value?

Now, instead of the index, you know the value of the element from the Python list.

Use remove() method.

my_list = ['p','r','o','b','l','e','m'] 

my_list.remove('p') 

print(my_list) 
# Output: ['r', 'o', 'b', 'l', 'e', 'm']

Using the pop() Method:

Instead of just deleting the element from the list, you also want to know the value of the deleted element, use the pop() method.

my_list = ['r', 'o', 'b', 'l', 'e', 'm'] 

print(my_list.pop(1)) 
# Output: 'o' 

print(my_list) 
# Output: ['r', 'b', 'l', 'e', 'm'] 

print(my_list.pop()) 
# Output: 'm' 

print(my_list) 
# Output: ['r', 'b', 'l', 'e']

Note: If you don’t provide an index to the pop() method, it removes and returns the last element from the list.

How to Delete all the Elements in the List?

Use clear() method. Instead of deleting the list, it deleted all the elements in the list. It returns an empty list.

my_list = ['p' 'r', 'o', 'b', 'l', 'e', 'm'] 

my_list.clear() 

print(my_list) 
# Output: []

Deleting Elements in a List by Assigning Empty Value:

Yeah, you can do that.

my_list = ['p','r','o','b','l','e','m'] 

my_list[2:3] = [] 
print(my_list) 
#output: ['p', 'r', 'b', 'l', 'e', 'm'] 

my_list[2:5] = [] 
print(my_list) 
#output: ['p', 'r', 'm']

How to iterate through a Python list?

Do you want to perform certain operations on each element in the given list?

You can iterate over a complete list using ‘for’ keyword.

for dev in ['Alice','Bob','Mark']: 
    print(dev, "is a developer.")

Output:

Alice is a developer.
Bob is a developer.
Mark is a developer.

How to get the list index and element in ‘for’ loop?

You can use enumerate() built-in function.

for ind, dev in enumerate(['Alice', 'Bob', 'Mark']): 
    print(ind, dev)

Output:

0 Alice
1 Bob
2 Mark

Note: Index starts with zero.

How to Convert Python List into a String?

You can use the join() method. It is a string method to covert the Python list into a string.

myList=['I', 'love', 'Python', 'Programming.'] 
print(" ".join(myList))

Output:

I love Python Programming.

Make sure, all the elements in the array list are strings.

If the elements in the list are integer you have to convert it to a string before using join() method.

How to Convert a List of Multiple Integers into a Single Integer?

For example, if the input is [1, 3, 5, 5], the output should be 1355.

Here is a simple solution for your query.

myList=[1, 3, 5, 5] 
print("Origional List: ",myList) 

#converting data type of each element in the list 
#from int to string. 
strList=[str(x) for x in myList] 
print("String List: ",strList) 

val = int(" ".join(strList)) 
print("Integer Value: "val)

Output:

Origional List: [1, 3, 5, 5]
String List: ['1', '3', '5', '5']
Integer Value: 1355

Sorting Python List

There are two ways you can sort the Python list.

  • using sorted() built-in-function
  • using sort() Python list method

sorted() built-in function:

>> listObj=[34,17,56]
sorted(listObj)
[17, 34, 56]
>> listObj
[34, 17, 56]

sort() Python list method:

>> listObj=[34,17,56]
>> sorted(listObj, reverse=True)
[56, 34, 17]

There are a lot of differences between the two sorting methods. I have explained it in the list sorting tutorial.

How to Check if Two Lists have Same Elements?

Here, we need to compare two lists. There are various methods we can use to check if the two lists have the same elements or not.

As we have already discuss, you can refer to this tutorial.

What is the Nested List?

When you add a complete Python list as an element of another list, it is called a nested list.

The syntax is pretty easy.

# nested list 
my_list = ["mouse", [8, 4, 6], ['a']]

How to access elements in the nested list?

# nested list 
nestedListObj = ["Happy",23, [2,7,1,5]] 

print(nestedListObj [2][1]) 
# Output: 7

Python List Methods

What are the Python list methods?

We saw all the list methods used for inserting, deleting, and updating the Python list. Summarizing those methods for comparative understanding.

List methods for For adding new elements:

  • append() – Add a new element to the end of the Python list
  • extend() – Add all elements from one Python list to the another list
  • insert() – Insert an item in the list at the given index

List methods for deleting elements:

  • remove() – Removes an item from the list
  • pop() – Removes and returns an element at the given index
  • clear() – Removes all items from the list

Other useful list methods:

  • index() – Returns the index of the first matched element
  • count() – Returns the number of matching elements in the list for a given element
  • sort() – Sort all the elements in a list in ascending order. You can also sort the elements in descending order by passing “reverse=True” parameter to sort() method.
  • reverse() – Reverse the order of all the elements in the list
  • copy() – Copy all the elements to the new list and returns a shallow copy of the list

Python List Built-in Functions

What are the built-in-function you can use with the Python list?

There are some built-in functions where you can pass the list as an argument and get the specific operation done with just one line.

  • all() – Return True if all elements in the list are true. Even for the empty list, this function returns True. If there is any single element as False, it returns False.
  • any() – Return True if any element of the list is true. If the list is empty, return False.
  • enumerate() – Return an enumerate object. It contains the index and value of all the elements of the list as a tuple. I have already given an example of it in our earlier part of this tutorial (Iteration through Python List).
  •  len() – Return the length (the number of elements) in the given list.
  • list() – Convert an iterable to a list. With this list() function you can convert tuple, string, set, and dictionary into the list.
  • sorted() – Return a new sorted list.
    Note: Instead of sorting the original list, it creates a new list with sorted elements.
  • sum() – Return the sum of all elements in the list. All the elements in the list should be integer data types.
  • cmp(list1, list2) – Compares elements of both lists.

Some Mathematical Operations on Python List using Built-in Functions:

>>> listObj=[34,56,56]
>>> len(listObj)
3
>>> max(listObj)
56
>>> min(listObj)
34
>>> sum(listObj)
146

List Comprehension

It is an advanced topic in the Python list.

What is list compression?

In simple terms, list compression is a technique where we write an expression followed by for statement inside square brackets.

Don’t get it?

No worry.

Check this example.

Write a program to create a list of first 5 even numbers.

multiplyOfTwo = [] for x in range(5): 
    multiplyOfTwo.append(2 *x) 

print(multiplyOfTwo)

Output:

[0, 2, 4, 6, 8]

Instead of writing those multiple lines, you can do the same job with just one line of code using the list comprehension technique.

multiplyOfTwo = [2 * x for x in range(5)]

You can also add more conditions in a list comprehension.

pow2 = [2 ** x for x in range(5) if x > 0] 

print(pow2)

Output:

[2, 4, 6, 8]

Based on the if-condition, this program only includes values which are greater than zero.

Conclusion

This is all about Python list tutorial. I have tested each code and spent a really good amount of time curating this complete this tutorial. If you like it, please write to me in the comment section and also share with your friends.

Some of the Python list programming examples:

If you enjoy and learn from this Python tutorial, I believe,  you will also like my Python dictionary tutorial. Just like a Python list, you will find everything you need to learn about Python dictionary.

If you have any specific question, write in the comment section. I’m here for you 😀

8 Comments

  1. Hi Aniruddha

    This function isn’t working for me what you showed in theory section :

    >>> sum(listObj)
    146

    I am trying to code one stuff in pycharm but getting no output

    numbers=[12,14]
    sum(numbers)

    output:
    =======
    C:\Users\mkar\PycharmProjects\test\venv\Scripts\python.exe C:/Users/mkar/PycharmProjects/test/testing.py

    Process finished with exit code 0

    1. Hi Madhumaya,

      Looks like you are able to run the program but you are not printing anything as an output.

      If you are running the Python code from .py flle, use print() function.

      ———–
      numbers=[12,14]
      print(sum(numbers))
      ———-

      Save this code in your .py file and execute.

  2. Hi Aniruddha Chaudhari, Very exhaustive and complete list. Keep it up. Look forward to other curated list on python.

  3. hi,

    You have a problem here. pls, check it.

    listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k'] 
     
    print('t' in listObj ) 
    #True 
     
    print('z' not in listObj ) 
    #false  
    

    the second false should be true.

    best regards
    Alireza

Leave a Reply

Your email address will not be published. Required fields are marked *