Bernard Aybouts - Blog - Miltonmarketing.com

Approx. read time: 3.4 min.

Post: Learn Python Lists

Lesson on Lists in Python

Lists in Python are a versatile and powerful tool for storing collections of items. They are similar to arrays in other programming languages but are more flexible as they can contain items of different types. You can add, remove, and iterate over elements in a list with ease. Let's dive deeper into the basics of lists, how to manipulate them, and see some practical examples.

Creating and Manipulating Lists

To create a list, you simply use square brackets []. You can initialize an empty list or create a list with initial elements.

Example 1: Creating and Appending to a List

# Initializing an empty list
mylist = []

# Appending elements to the list
mylist.append(1)
mylist.append(2)
mylist.append(3)

# Accessing elements in the list by index
print(mylist[0])  # prints 1
print(mylist[1])  # prints 2
print(mylist[2])  # prints 3

# Iterating over the list and printing elements
for x in mylist:
    print(x)  # prints 1, 2, 3

Accessing Elements in a List – Learn Python Lists

Lists in Python are zero-indexed, meaning the first element is at index 0. Accessing an element at an index that does not exist will raise an IndexError.

Example 2: Accessing List Elements and Handling Index Errors

mylist = [1, 2, 3]

# Trying to access an element at an index that doesn't exist
try:
    print(mylist[10])  # This will raise an IndexError
except IndexError as e:
    print(f"Error: ")

Practical Exercise

In this exercise, you'll practice adding elements to lists and accessing specific elements. You'll need to add numbers and strings to their respective lists using the append method. Additionally, you'll extract the second name from a list of names.

Exercise: Fill and Access Lists

# Initialize empty lists
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]

# Adding numbers to the 'numbers' list
numbers.append(1)
numbers.append(2)
numbers.append(3)

# Adding strings to the 'strings' list
strings.append("hello")
strings.append("world")

# Accessing the second name in the 'names' list
second_name = names[1]

# Printing the lists and the second name
print(numbers)         # Output: [1, 2, 3]
print(strings)         # Output: ["hello", "world"]
print(f"The second name on the names list is ")  # Output: The second name on the names list is Eric

Explanation – Learn Python Lists

  • Creating Lists: numbers, strings, and names are initialized.
  • Appending Elements: Elements are added to numbers and strings using the append method.
  • Accessing Elements: The second element of names is accessed using names[1].
  • Output: The contents of the lists and the second name are printed.

Additional Examples

Example 3: Mixed Data Types in Lists

lists can contain elements of different data types, including other lists.

mixed_list = [1, "hello", 3.14, [4, 5, 6]]
print(mixed_list)  # Output: [1, 'hello', 3.14, [4, 5, 6]]

# Accessing a sub-list element
print(mixed_list[3][1])  # Output: 5

Example 4: List Comprehensions

# Creating a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Conclusion – Learn Python Lists

Lists are a fundamental data structure in Python, providing a flexible and efficient way to handle collections of items. Whether you're adding elements, iterating over them, or accessing specific items, lists offer a straightforward syntax that makes them easy to use.

For hands-on practice, you can use online Python compilers like Trinket.io to run and modify the examples provided in this lesson. Happy coding!

Additional Exercise – Learn Python Lists

In this exercise, you will need to create a list of the first 5 even numbers and a list of the first 5 odd numbers. Then, combine these two lists into a single list and print the combined list.

Exercise:

# Create lists of even and odd numbers
even_numbers = []
odd_numbers = []

# Add first 5 even numbers to the 'even_numbers' list
for i in range(2, 11, 2):
    even_numbers.append(i)

# Add first 5 odd numbers to the 'odd_numbers' list
for i in range(1, 10, 2):
    odd_numbers.append(i)

# Combine both lists
combined_list = even_numbers + odd_numbers

# Print the combined list
print(combined_list)  # Output: [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]

Answer Key:

# Expected output
# [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
For privacy reasons YouTube needs your permission to be loaded. For more details, please see our Privacy Policy – Legal Disclaimer – Site Content Policy.

The Longevity Blueprint: AI-Powered Health Optimization

Current step:1AI-Human Medical Analyzer: Smarter, Personalized Health
2AI-Human Medical Analyzer: Smarter, Personalized Health

> SYS.HEALTH: AI-Human Medical Analyzer_

// Revolutionize Your Diagnostics

Experience the perfect blend of cutting-edge AI precision and expert human care. Our revolutionary analyzer turns your raw health data into personalized, actionable insights tailored just for you.

> INITIALIZING_BIOMETRIC_SCAN...

[+] DATA_INPUT

Securely upload complex health parameters, including lab bloodwork and comprehensive medical history.

[+] PROCESSING

Advanced algorithmic parsing combined with human-level oversight ensures hyper-accurate data interpretation.

[+] OUTPUT_MATRIX

Receive smarter, faster, and truly personalized care strategies to take immediate charge of your health journey.

A name/nickname is required to continue.

> TRANSLATION_MATRIX_ACTIVE...
[ LANG_EN ]
Knowledge Heals, Prevention Protects
[ LANG_HI ]
ज्ञान ठीक करता है, रोकथाम सुरक्षा करती है
[ LANG_ZH ]
知识治愈,预防保护
[ LANG_JA ]
知識は癒し、予防は守る
[ LANG_HE ]
הידע מרפא, המניעה מגנה
[ LANG_AR ]
المعرفة تُشفي، والوقاية تحمي
[ LANG_FR ]
La connaissance guérit, la prévention protège

> SYS.AUTH: Data Processing Consent_

[ AWAITING_AUTHORIZATION ] By providing consent, you allow us to process your uploaded data through our proprietary AI-Human analysis system.

  • [+] SECURE_REVIEW: This ensures your information is carefully reviewed using advanced AI technology and certified professional oversight to deliver personalized health insights.
  • [+] PRIVACY_LOCK: Your privacy is our strict priority. Your data will only be used for this specific diagnostic purpose.

> SYS.UPLOAD: Share Medical Records [OPTIONAL]_

[ USER_CONTROL_ACTIVE ] Uploading your medical records during registration is entirely optional. You can choose to bypass this step and provide data later if it suits your timeline.

You dictate the data flow: share as much or as little as you’re comfortable with, and let us guide you toward better health.

[+] FORMAT_SUPPORT

We accept all file formats, including photos, PDFs, text documents, and raw official medical data.

[+] DATA_YIELD

Increased inputs correlate with higher precision. The more info you share, the better we tailor your personalized insights.

> NEXT_STEPS: Post-Registration Protocol_

Once your registration is complete, a human specialist from our team will personally reach out to you within 3-10 business days. We will discuss your health journey and map out exactly how we can support you.

About the Author: Bernard Aybout (Virii8)

Avatar Of Bernard Aybout (Virii8)
I am a dedicated technology enthusiast with over 45 years of life experience, passionate about computers, AI, emerging technologies, and their real-world impact. As the founder of my personal blog, MiltonMarketing.com, I explore how AI, health tech, engineering, finance, and other advanced fields leverage innovation—not as a replacement for human expertise, but as a tool to enhance it. My focus is on bridging the gap between cutting-edge technology and practical applications, ensuring ethical, responsible, and transformative use across industries. MiltonMarketing.com is more than just a tech blog—it's a growing platform for expert insights. We welcome qualified writers and industry professionals from IT, AI, healthcare, engineering, HVAC, automotive, finance, and beyond to contribute their knowledge. If you have expertise to share in how AI and technology shape industries while complementing human skills, join us in driving meaningful conversations about the future of innovation. 🚀