Python List: A Comprehensive Guide with Examples

Master Python list with this in-depth guide! Learn about list creation, operations, techniques, and more with code examples to enhance your programming skills.

What is a Python List?

A Python list is a collection of values enclosed in square brackets [], separated by commas. For example, [100, 250, 30] is a list of three numbers.

Python Lists
Python Lists

Key Characteristics of List

  • Creation: Python Lists can be created using square brackets [] or the list() function.
  • Element Types: Python Lists can store homogeneous (same type) and heterogeneous (different types) elements.
  • Dynamic Size: Python Lists can grow or shrink dynamically.
  • Insertion Order: The order of elements is preserved
    • Example:    input =  output ([10, 20, 30] = [10, 20, 30]).
  • Duplicates: Python Lists allow duplicate elements.
  • Mutability: Python Lists are mutable, meaning their contents can be changed after creation.
  • Indexing: Elements can be accessed using both positive (left to right) and negative (right to left) indices.

Creating Python List

1. Creating a empty list

empty_lst = [] or list()
print(empty_lst)  # Output: []
print(type(empty_lst)) # Output: <class ‘list’>

2. Creating list with elements

student_info = ["Hari", 10, 35]
print(student_info) # Output: ["Hari", 10, 35]

3. Creating a python list by using list(parameter1) predefined function

  • You can create a list using the list(parameter1) function, which takes only one argument.
  • The argument must be a sequence object (like a range, list, set, or tuple); otherwise, it will cause an error.
rng=range(0, 10)
lst=list(rng)
print(lst) #Output: [0,1,2,3,4,5,6,7,8,9]

4. Dynamic Python List Input

# Accepting dynamic input for a list
user_list = eval(input("Enter List: "))
print(user_list)
print(type(user_list))

#Output:
Enter List: [10, 20, 30, 40]
[10, 20, 30, 40]             
<class 'list'>              

5. with split() function:

s = "Data science is a fascinating field of study."
l = s.split()
print(l) 
print(type(l))

# Output:
['Data', 'science', 'is', 'a', 'fascinating', 'field', 'of', 'study.']
<class 'list'>                                                           

Accessing elements from python list

We can access values or items from list by using,

  • indexing
  • slicing
  • loops

Examples:

Indexing

shopping_list = ['milk', 'bread', 'eggs', 'butter']
print(shopping_list[1])  # Output: 'bread'

Slicing

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[:])     # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (Full list)
print(numbers[::])    # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (Full list, step 1)
print(numbers[0:7])   # Output: [1, 2, 3, 4, 5,6,7] (Slicing the first 7 elements)

Reverse the list:

l = [1, 2, 3, 4, 5]
print(l)
print(l[::-1]) # Output: [5,4,3,2,1]

Loops

tasks = ['clean the house', 'pay bills', 'grocery shopping']
for task in tasks:
    print(task)

# Output:
clean the house
pay bills
grocery shopping

Python Lists is Mutable

Once we have created a list object, we can modify the values or elements in the existing list object.

# Define a list
fruits = ["apple", "banana", "cherry", "date"]
print(fruits)
# Access and print the first element before modification
print("Before modifying fruits[1]:", fruits[1])
# Modify the second element
fruits[1] = "blueberry"
# Access and print the modified element
print("After modifying fruits[1]:", fruits[1])
# Print the modified list
print(fruits)

# Output:
['apple', 'banana', 'cherry', 'date']
Before modifying fruits[1]: banana
After modifying fruits[1]: blueberry
['apple', 'blueberry', 'cherry', 'date']

Common List Functions

FunctionDescriptionExampleOutput
len(list)Returns the number of elements in a list.len([1, 2, 3, 4])4
min(list)Returns the smallest element in the list.min([5, 2, 9, 1])1
max(list)Returns the largest element in the list.max([5, 2, 9, 1])9
reversed(list)Returns an iterator that accesses the list in reverse order.list(reversed([1, 2, 3]))[3, 2, 1]
sorted(list)Returns a sorted list without modifying the original list.sorted([3, 1, 2])[1, 2, 3]

Examples Using All Functions Together

my_list = [7, 2, 5, 1, 9]

# 1. len() - Get the length of the list
print(f"Length of the list: {len(my_list)}")  # Output: 5

# 2. min() - Find the minimum value in the list
print(f"Smallest element: {min(my_list)}")  # Output: 1

# 3. max() - Find the maximum value in the list
print(f"Largest element: {max(my_list)}")  # Output: 9

# 4. reversed() - Get the list in reverse order
print(f"Reversed list: {list(reversed(my_list))}")  # Output: [9, 1, 5, 2, 7]

# 5. sorted() - Get the sorted version of the list
print(f"Sorted list: {sorted(my_list)}")  # Output: [1, 2, 5, 7, 9]

List Methods

MethodDescription
list.append(item)Adds an item to the end of the list.
list.extend(iterable)Adds elements from an iterable to the end.
list.insert(index, item)Inserts an item at a specified index.
list.remove(item)Removes the first occurrence of an item.
list.pop(index)Removes and returns an item at the specified index.
list.clear()Removes all items from the list.
list.index(item)Returns the index of the first occurrence of an item.
list.count(item)Returns the number of occurrences of an item.
list.sort()Sorts the items in the list in ascending order.
list.reverse()Reverses the order of the items in the list.

** dir(list) predefined function helps us get all methods.

Example for each method

1. list.append(item): Adds an item to the end of the list

fruits = ['apple', 'banana']
fruits.append('orange')
print(fruits)  # Output: ['apple', 'banana', 'orange']

2. list.extend(iterable): Extends the list by appending elements from an iterable.

fruits = ['apple', 'banana']
fruits.extend(['orange', 'grape'])
print(fruits)  # Output: ['apple', 'banana', 'orange', 'grape']

3. list.insert(index, item): Inserts an item at a specified index.

fruits = ['apple', 'banana']
fruits.insert(1, 'orange')
print(fruits)  # Output: ['apple', 'orange', 'banana']

4. list.remove(item): Removes the first occurrence of an item from the list.

fruits = ['apple', 'banana', 'orange']
fruits.remove('banana')
print(fruits)  # Output: ['apple', 'orange']

5. list.pop(index): Removes and returns the item at the specified index (or the last item if no index is specified).

fruits = ['apple', 'banana', 'orange']
removed_item = fruits.pop(1)
print(removed_item)  	# Output: 'banana'
print(fruits)           # Output: ['apple', 'orange']

6. list.clear(): Removes all items from the list.

fruits = ['apple', 'banana', 'orange']
fruits.clear()
print(fruits)  # Output: []

7. list.index(item): Returns the index of the first occurrence of an item, if item not found, it returns error.

list.rindex(item): Returns the index of the last occurrence of an item, if item not found, it returns error.

fruits = ['apple', 'banana', 'orange', 'mango', 'banana']
index_of_banana = fruits.index('banana')
rindex_of_banana = fruits.rindex('banana')
print(index_of_banana)  # Output: 1
print(rindex_of_banana)  # Output: 4

8. list.count(item): Returns the number of occurrences of an item.

fruits = ['apple', 'banana', 'orange', 'banana']
count_of_banana = fruits.count('banana')
print(count_of_banana)  # Output: 2

9. list.sort(): Sorts the items of the list in place.

fruits = ['banana', 'orange', 'apple']
fruits.sort()
print(fruits)  # Output: ['apple', 'banana', 'orange']

10. list.reverse(): Reverses the elements of the list in place.

fruits = ['apple', 'banana', 'orange']
fruits.reverse()
print(fruits)  # Output: ['orange', 'banana', 'apple']

Mathematical + and * operators

  • Concatenation (+): Combines two or more lists into one.
  • Repetition (*): Repeats a list a specified number of times.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Concatenation
combined_list = list1 + list2  # Output: [1, 2, 3, 4, 5, 6]
# Repetition
list3 = [1, 2, 3] 
repeated_list = list3 * 3 # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

Membership operators

  • in Operator: Returns True if the element is in the list; otherwise, False.
  • not in Operator: Returns True if the element is not in the list; otherwise, False.
fruits = ['apple', 'banana', 'cherry', 'date']
print('banana' in fruits)      	# Output: True
print('grape' not in fruits)    # Output: True
print('cherry' in fruits)       # Output: True
print('orange' in fruits)   	# Output: False

Nested Lists

A nested list is a list that contains one or more other lists as a value or element.

# Define a nested list
students = [
    ["Alice", [85, 90, 78]],
    ["Bob", [88, 92, 80]],
    ["Charlie", [90, 85, 95]]
]

# Loop through the nested list to access names and grades
for student in students:
    name = student[0]
    grades = student[1]
    print(f"Grades for {name}:")
    for grade in grades:
        print(grade)

# Output:
Grades for Alice:
85
90
78
Grades for Bob:
88
92
80
Grades for Charlie:
90
85
95

List Comprehension

  • Definition: List comprehensions provide a concise way to create new lists from iterable objects like lists, sets, tuples, dictionaries, and ranges.
  • Conciseness: They allow you to write shorter and more readable code.

Syntax: new_list = [expression for item in seq_object if condition]

  • seq_object: Represents a list, set, tuple, dictionary, or range object.
  • Result: The result is a new list based on the specified conditions.
# Creating a list of squares for even numbers from 0 to 9
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)  # Output: [0, 4, 16, 36, 64]

List Comprehension with Ternary Operator

Syntax: new_list = [(true_value if condition else false_value) for item in iterable if condition]

# Creating a list that labels numbers as 'even' or 'odd'
numbers = range(10)
labels = ['even' if x % 2 == 0 else 'odd' for x in numbers]
print(labels)  

# Output: ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

Conclusion

Lists are a fundamental data type in Python, providing flexible and powerful methods to handle groups of items efficiently. Their mutability and rich set of methods make them suitable for various tasks, from simple data storage to difficult or complex data manipulation.

Check out our full Python guide here. : Learn From KSR Datavizon | Explore and Read Our Blogs Written By Our Industry Expert

Knowledge Check

Related Article No.4

https://blog.ksrdatavision.com/python/input-and-output-in-python
Data Analytics with Power Bi and Fabric
Could Data Engineer
Data Analytics With Power Bi Fabic
AWS Data Engineering with Snowflake
Azure Data Engineering
Azure & Fabric for Power bi
Full Stack Power Bi
Subscribe to our channel & Don’t miss any update on trending technologies

Kick Start Your Career With Our Data Job

Master Fullstack Power BI – SQL, Power BI, Azure Cloud & Fabric Tools
Master in Data Science With Generative AI Transform Data into Business Solutions
Master Azure Data Engineering – Build Scalable Solutions for Big Data
Master AWS Data Engineering with Snowflake: Build Scalable Data Solutions
Transform Your Productivity With Low Code Technology: Master the Microsoft Power Platform

Social Media channels

► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizon
► KSR Datavizon Instagram :- https://www.instagram.com/ksr_datavision
► KSR Datavizon Face book :- https://www.facebook.com/KSRConsultingServices
► KSR Datavizon Playstore :- https://play.google.com/store/apps/details?id=com.datavizon.courses&hl=en-IN
► KSR Datavizon Appstore :- https://apps.apple.com/in/app/ksr-datavizon/id1611034268

Related Posts

Leave a Reply

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