List_in_Python
List_in_Python
Introduction to Lists
What is a List?
•List is a collection of items that are ordered, changeable, and allow duplicate
values.
•Lists are one of the most commonly used data types in Python.
•Lists are written with square brackets.
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits)
Output:
["apple", "banana", "cherry"]
Difference Between List, Tuple and Set
Key Differences
Feature List Tuple Set
Syntax [] () {}
Mutable? Yes No Partially*
Example fruits = ["apple"] fruits = ("apple") fruits = {"apple"}
*Note: Sets are unchangeable in structure, but their elements can be added or removed.
Various Operations on Lists
Creating a List
•Example:
numbers = [1, 2, 3, 4]
print(numbers)
•Output:
[1, 2, 3, 4]
2. Adding Elements to a List
•Syntax:
list[start:end] (end index is exclusive).
•Example 1:
fruits = ["apple", "banana", "cherry", "grape"]
print(fruits[1:3])
• Output:
["banana", "cherry"]
5. List Slicing
•Example 2:
fruits = ["apple", "banana", "cherry", "grape"]
print(fruits[-3:-1])
• Output:
['banana', 'cherry’]
•Example 3:
fruits = ["apple", "banana", "cherry", "grape"]
print(fruits[1:])
• Output:
['banana', 'cherry', 'grape’]
5. List Slicing
• Example 4:
fruits = ["apple", "banana", "cherry", "grape"]
print(fruits[:1])
• Output:
[‘apple’]
• Example 5:
fruits = ["apple", "banana", "cherry", "grape"]
print(fruits[:])
• Output:
[‘apple’, 'banana', 'cherry', 'grape’]
6. Traversing a List
1. Create a list of your favorite movies and add two more using append().
2. Remove a movie from the list using remove().
3. Replace one movie with another of your choice.
4. Print the list in reverse order using slicing.
5. Traverse the list and print each movie in uppercase.