List example practice

George's Python
2 min readFeb 28, 2023

--

Photo by Daniel Chekalov on Unsplash

Creating a list of numbers and printing it:

numbers = [1, 2, 3, 4, 5]
print(numbers)

Output:

Creating a list of strings and printing it:

fruits = ["apple", "banana", "cherry", "orange"]
print(fruits)

Output:

Creating a mixed list and printing it:

mixed_list = [1, "apple", True, 3.14]
print(mixed_list)

Output:

Accessing elements of a list by index:

fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[0]) # Output: "apple"
print(fruits[2]) # Output: "cherry"

Accessing elements of a list by negative index:

fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[-1]) # Output: "orange"
print(fruits[-2]) # Output: "cherry"

Slicing a list to get a range of elements:

fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[1:3]) # Output: ["banana", "cherry"]

Slicing a list to get elements from a starting index to the end:

fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[2:]) # Output: ["cherry", "orange"]

Slicing a list to get elements from the beginning to an ending index:

fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[:2]) # Output: ["apple", "banana"]

Modifying elements of a list by index:

fruits = ["apple", "banana", "cherry", "orange"]
fruits[1] = "kiwi"
print(fruits) # Output: ["apple", "kiwi", "cherry", "orange"]

Modifying a range of elements of a list using slicing:

fruits = ["apple", "banana", "cherry", "orange"]
fruits[1:3] = ["kiwi", "melon"]
print(fruits) # Output: ["apple", "kiwi", "melon", "orange"]

Adding a new element to the end of a list using append():

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

Adding multiple elements to the end of a list using the + operator:

fruits = ["apple", "banana", "cherry", "orange"]
fruits += ["pear", "grape"]
print(fruits) # Output: ["apple", "banana", "cherry", "orange", "pear", "grape"]

I hope these examples help you understand how to work with lists in Python!

for the Next step Click here

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

George's Python
George's Python

Written by George's Python

I write to help how to learn Python

No responses yet

Write a response