Site icon Towards Advanced Analytics Specialist & Analytics Engineer

Python Crash Course | Python Lists Uncovered: A Comprehensive Guide with Coding Examples and Explanations

Python Crash Course | Python Lists Uncovered: A Comprehensive Guide with Coding Examples and Explanations

 

Lists are a fundamental data structure in Python, allowing you to store and manipulate collections of items. Python lists are versatile, easy to use, and provide a wide range of built-in functions to perform various operations. This comprehensive guide will delve into Python lists, complete with coding examples and explanations to help you master this essential data structure.

Creating and Initializing Lists

Empty Lists

To create an empty list, use a pair of square brackets or the list() constructor.

Example:

empty_list1 = []
empty_list2 = list()

print(empty_list1, empty_list2)  # Output: [] []

Lists with Elements

To create a list with elements, enclose the items in square brackets, separated by commas.

Example:

fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]

print(fruits, numbers)  # Output: ['apple', 'banana', 'cherry'] [1, 2, 3, 4, 5]

Lists with Mixed Data Types

Python lists can store items of different data types, such as strings, numbers, and even other lists.

Example:

mixed_list = ['apple', 42, 3.14, [1, 2, 3]]

print(mixed_list)  # Output: ['apple', 42, 3.14, [1, 2, 3]]

Accessing List Elements

Indexing

You can access individual list elements using their index. Indexing in Python lists starts at 0 for the first element and increases by 1 for each subsequent element.

Example:

fruits = ['apple', 'banana', 'cherry']

first_fruit = fruits[0]
second_fruit = fruits[1]
last_fruit = fruits[-1]

print(first_fruit, second_fruit, last_fruit)  # Output: 'apple' 'banana' 'cherry'

Slicing

To access a range of elements in a list, use slicing with the syntax list[start:stop:step]. The start index is inclusive, while the stop index is exclusive. The step parameter is optional and defines the increment between indices.

Example:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

first_five = numbers[:5]
even_numbers = numbers[::2]
reversed_numbers = numbers[::-1]

print(first_five, even_numbers, reversed_numbers)
# Output: [0, 1, 2, 3, 4] [0, 2, 4, 6, 8] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Manipulating Lists

Adding Elements

To add elements to a list, you can use the append() method for inserting an item at the end of the list or the insert() method for placing an item at a specified index.

Example:

fruits = ['apple', 'banana', 'cherry']

fruits.append('orange')
fruits.insert(1, 'grape')

print(fruits)  # Output: ['apple', 'grape', 'banana', 'cherry', 'orange']

Removing Elements

To remove elements from a list, use the remove() method to delete a specific item by value, the pop() method to remove and return an item by index, or the del keyword to delete an item or a range of items by index.

Example:

fruits = ['apple', 'grape', 'banana', 'cherry', 'orange']

fruits.remove('grape')
popped_fruit = fruits.pop(1)
del fruits[1:3]

print(fruits, popped_fruit)  # Output: ['apple'] 'banana'

Updating Elements

To update an element in a list, assign a new value to the item at the desired index.

Example:

fruits = ['apple', 'grape', 'banana', 'cherry', 'orange']

fruits[1] = 'blueberry'

print(fruits)  # Output: ['apple', 'blueberry', 'banana', 'cherry', 'orange']

List Methods and Functions

Sorting Lists

To sort a list in ascending order, use the sort() method. To sort a list in descending order, provide the reverse=True argument.

Example:

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

numbers.sort()
print(numbers)  # Output: [1, 2, 3, 4, 5]

numbers.sort(reverse=True)
print(numbers)  # Output: [5, 4, 3, 2, 1]

Reversing Lists

To reverse the order of a list, use the reverse() method.

Example:

fruits = ['apple', 'blueberry', 'banana', 'cherry', 'orange']

fruits.reverse()

print(fruits)  # Output: ['orange', 'cherry', 'banana', 'blueberry', 'apple']

Counting Occurrences

Use the count() method to determine the number of occurrences of an item in a list.

Example:

numbers = [1, 2, 3, 2, 1, 2, 3, 1, 1]

count_ones = numbers.count(1)

print(count_ones)  # Output: 4

List Comprehensions

List comprehensions provide a concise way to create new lists based on existing lists, applying a specific condition or transformation to each element.

Example:

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

squares = [x ** 2 for x in numbers]
even_numbers = [x for x in numbers if x % 2 == 0]

print(squares, even_numbers)  # Output: [1, 4, 9, 16, 25] [2, 4]

Summary

Python lists are an essential data structure that allows you to store and manipulate collections of items effectively. This comprehensive guide has provided you with an in-depth understanding of Python lists, including creating and initialising lists, accessing and modifying list elements, using various list methods and functions, and utilising list comprehensions. By mastering Python lists and their capabilities, you can efficiently handle collections of data and enhance the functionality and versatility of your Python programs.

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)


Learn by Coding: Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!

Exit mobile version