0% found this document useful (0 votes)
11 views3 pages

Python Lists: A Comprehensive Guide

Uploaded by

sandboxpmu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Python Lists: A Comprehensive Guide

Uploaded by

sandboxpmu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Lists - Explanation with Examples

1. What is a List?
A list is an ordered, mutable collection of items, which can be of different types. Lists allow
duplicates.

# Creating a list
my_list = [10, "apple", 3.14, 10]
print(my_list)

Output:

[10, 'apple', 3.14, 10]

2. Accessing Elements

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


print(fruits[0]) # first element
print(fruits[-1]) # last element

Output:

apple
cherry

3. Modifying Elements

fruits[1] = "mango"
print(fruits)

Output:

['apple', 'mango', 'cherry']

4. Adding Elements

1
[Link]("orange") # add at end
[Link](1, "kiwi") # insert at index 1
print(fruits)

Output:

['apple', 'kiwi', 'mango', 'cherry', 'orange']

5. Removing Elements

[Link]("kiwi") # remove by value


[Link](2) # remove by index
print(fruits)

Output:

['apple', 'mango', 'orange']

6. Length of List

print(len(fruits))

Output:

7. Looping Through List

for fruit in fruits:


print(fruit)

Output:

apple
mango
orange

2
8. Slicing List

numbers = [10, 20, 30, 40, 50]


print(numbers[1:4]) # index 1 to 3
print(numbers[:3]) # start to index 2
print(numbers[2:]) # index 2 to end

Output:

[20, 30, 40]


[10, 20, 30]
[30, 40, 50]

9. Common Methods

nums = [3,1,2]
[Link]() # sort list
[Link]() # reverse list
[Link](4) # add 4
print(nums)

Output:

[3, 2, 1, 4]

Summary
• Lists store multiple items in a single variable.
• They are ordered, mutable, and allow duplicates.
• Lists support indexing, slicing, looping, and many built-in methods for easy data
manipulation.

You might also like