Python for Beginners begunpro

Python Learning Day 12-13

Python

Welcome to the exploration of lists in Python! Lists are versatile data structures that allow you to store and manipulate collections of items. In this tutorial, we’ll dive into the basics of lists and cover fundamental operations you can perform on them.

What is a List?

Think of a list in Python like a shopping list in real life. It’s a way to keep track of items, and just like a shopping list can have different things on it, a Python list can hold different types of data, such as numbers, words, or a mix of both.

Creating a List

				
					# Example: Creating a list
fruits = ["apple", "banana", "cherry"]
				
			

Here, we created a list named fruits that contains three items: “apple”, “banana”, and “cherry”.

Accessing Elements

				
					# Example: Accessing elements
first_fruit = fruits[0]
second_fruit = fruits[1]
last_fruit = fruits[-1]
				
			

In Python, we start counting from 0. So, fruits[0] gives us the first item (“apple”), fruits[1] gives the second item (“banana”), and fruits[-1] gives the last item (“cherry”).

Modifying Lists

				
					# Example: Modifying lists
fruits[1] = "orange"  # Change the second item to "orange"
fruits.append("grape")  # Add a new item "grape" to the end
fruits.insert(1, "kiwi")  # Insert "kiwi" at the second position
				
			

Here, we’re updating, adding, and inserting items into our list.

Removing Elements

				
					# Example: Removing elements
removed_fruit = fruits.pop(1)  # Remove and get the item at the second position
fruits.remove("cherry")  # Remove the item with the value "cherry"
				
			

We can take items out of the list using pop() or remove().

List Slicing

				
					# Example: List slicing
selected_fruits = fruits[1:3]  # Get items at positions 1 and 2
				
			

List slicing allows us to grab a portion of the list. Here, fruits[1:3] gets us the second and third items.

List Concatenation

				
					# Example: List concatenation
more_fruits = ["grape", "melon"]
combined_fruits = fruits + more_fruits
				
			

We can combine two lists using the + operator.

List Length

				
					# Example: List length
num_fruits = len(fruits)
				
			

len() gives us the number of items in the list.

Practical Exercise: Shopping List

				
					# Exercise: Shopping List
shopping_list = ["apple", "banana", "bread", "milk", "eggs"]

shopping_list.extend(["cheese", "tomatoes"])
shopping_list[2] = "whole wheat bread"
removed_item = shopping_list.pop()

print("Final Shopping List:", shopping_list)
print("Removed Item:", removed_item)
				
			

In this exercise, we’re updating, adding, removing, and printing our shopping list.

Lists in Python are powerful tools for organizing and manipulating data. As you practice, you’ll become more comfortable using them in your programs. Happy coding!

1 thought on “Python Learning Day 12-13

Comments are closed.