Python Lists: A Comprehensive Guide with Codes and Examples in 2023

Article by: Manish Methani

Last Updated: October 5, 2021 at 2:04pm IST
6 min 56 sec read

Introduction to Python Lists

In Python, a list is a collection of ordered, mutable, and heterogeneous elements. Lists are one of the most commonly used data types in Python as they allow you to store and manipulate multiple items in a single variable.

Creating a Python List

You can create a Python list using square brackets [] and separating each element with a comma. For example:

my_list = [1, 2, 3, "hello", True]

In this example, we have created a list containing integers, a string, and a boolean value.

Accessing Elements in a Python List

You can access elements in a Python list using their index value. The index value starts from 0 for the first element and increases by 1 for each subsequent element. For example:

my_list = [1, 2, 3, "hello", True]
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: hello

You can also use negative indexing to access elements from the end of the list. For example:

my_list = [1, 2, 3, "hello", True]
print(my_list[-1]) # Output: True
print(my_list[-2]) # Output: hello

Modifying a Python List

You can modify elements in a Python list by assigning new values to them. For example:

my_list = [1, 2, 3, "hello", True]
my_list[3] = "world"
print(my_list) # Output: [1, 2, 3, "world", True]

In this example, we have modified the element at index 3 from "hello" to "world".

Adding and Removing Elements from a Python List

You can add elements to a Python list using the append() method. For example:

my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

You can also remove elements from a Python list using the remove() method. For example:

my_list = [1, 2, 3, 4]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4]

You can also remove elements from a Python list using the del keyword. For example:

my_list = [1, 2, 3, 4]
del my_list[2]
print(my_list) # Output: [1, 2, 4]

The basic example of List

# Create a list
ls = [5, 7, 25]

# Prints the type of the variable
print(type(ls))

# Print the contents of the list
print(ls)

# elementwise indexing in the list
print(ls[0], ls[1], ls[2])

# Append an element at the end of the list
ls.append(45)
print(ls)

# Remove and return the last element of the list
x = ls.pop()
print(x, ls) 

Example 2

# Unlike arrays, list can contain elements of different datatypes
ls = ["codzify", ".com", 23]

# Print the contents of the list
print(ls)

# indexing in the list
print(ls[0], ls[1], ls[2])

# Append an element at the end of the list
ls.append("hello world")
print(ls)

# Remove and return the last element of the list
x = ls.pop()
print(x, ls) 

Slicing a Python List

You can slice a Python list to extract a subset of elements from it. Slicing is done using the colon : operator. For example:

my_list = [1, 2, 3, "hello", True]
print(my_list[1:4]) # Output: [2, 3, "hello"]

In this example, we have sliced the list to extract elements from index 1 to index 3.

Try to execute the code to see the output.

ls = list(range(6))
print(ls)

# Negative Indexing is also possible, it will print from the end of the list
print(ls[-1], ls[-2], ls[-3])

# Get a sublist starting from index 1 to 3 (the last index is exclusive)
print(ls[1:4])

# Get a sublist starting from index 2 to the end
print(ls[2:])

# Get a sublist from start to index 3 (the last index is exclusive)
print(ls[:4])

# Get the whole list
print(ls[:])

# Assign a new sublist to a slice
ls[2:4] = ["codzify", "python"]
print(ls) 

Iterating over a Python List

You can iterate over a Python list using a for loop. For example:

my_list = [1, 2, 3, 4]
for element in my_list:
    print(element)

List Comprehensions

List comprehension is a powerful feature of Python programming that allows you to create a new list by applying a transformation to each element of an existing list. It is a concise and elegant way to write code and can help to simplify complex algorithms. With list comprehension, you can avoid writing lengthy code using for loops and if statements. This technique is widely used in data processing and manipulation tasks, and it can help to improve the efficiency and readability of your code.

To understand the concept we will demonstrate to you using the old traditional method to write programs and what you can do using python list comprehension.

Example 1:

Using an old traditional way find the square of numbers in python.

# Traditional way
nums = list(range(1,5))
squares = []
for x in nums:
 squares.append(x ** 2)
 print(squares) 

Using List Comprehension find the square of numbers in python.

# creates a list from range 1 to 5
nums = list(range(1,5))
squares = [x ** 2 for x in nums]
print(squares) 

Example 2:

Find the even and odd numbers from 1 to 10 using old traditional way

# creates a list from range 1 to 10
nums = list(range(10))
even = []
odd = [] 
for i in nums:
 if i%2 == 0:
   even.append(i)
  else:
   odd.append(i)
print("Even Numbers: ", even)
print("Odd Numbers : ", odd) 

Find the even and odd numbers from 1 to 10 using List Comprehension

nums = list(range(10))
even = [x for x in nums if x%2 == 0]
odd = [x for x in nums if x%2 != 0]
print("Even Numbers: ", even)
print("Odd Numbers : ", odd) 

Watch Video Tutorials at Codzify YouTube Channel:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: teamcodzify@gmail.com