List-Tuple and Sets
List-Tuple and Sets
List
An ordered, mutable (changeable) collection that can contain a variety of data types is called a list
in Python. You can store integers, texts, floats, or even other lists with lists, which are defined with
square brackets [].
Syntax
Empty list
my_list = []
Mixed list
mixed = [1, "hello", 3.14, True]
List slicing
With Python's list slicing feature, you may specify a range of indices for finding particular parts
of a list. The fundamental slicing syntax is:
new_list = my_list[start:stop:step]
my_list = [10, 20, 30, 40, 50, 60, 70]
my_list[1:4]
my_list[:3]
my_list[3:]
my_list[0:7:2]
my_list[-5:-2]
my_list[::-1]
21
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
List concatenation
In Python, list concatenation enables you to merge two or more lists into one. Here are a few
methods for doing it:
22
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
List in-operator
It is usual practice to traverse over the list's elements and perform operations on them by using a
list in a for loop. The following explains how lists can be used in for loops:
my_list = [1, 2, 3, 4, 5]
23
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
Let’s practice
Task
1. Create an empty list and print it.
2. Create a list with integers from 1 to 10 and print it.
3. Create a list with mixed data types (e.g., integer, string, float, boolean) and print it.
4. Create a nested list (a list inside a list) and print it.
5. Given a list my_list = [10, 20, 30, 40, 50, 60, 70], perform the following slicing operations:
a. my_list[1:4]
b. my_list[:3]
c. my_list[3:]
d. my_list[0:7:2]
e. my_list[-5:-2]
f. my_list[::-1]
6. Concatenate two lists: list1 = [1, 2, 3] and list2 = [4, 5, 6] and print the result.
7. Repeat the list [1, 2, 3] 3 times and print the result.
8. Repeat element [5] four times and print the result.
9. Create a list_numbers = [10, 20, 30, 40, 50] and perform the following operations:
a. Find the length of the list using len().
b. Calculate the sum of the list using sum().
c. Find the minimum and maximum values using min() and max().
d. Sort the list using sorted() and print the sorted list.
e. Find the index of an element using index().
f. Count how many times an element appears in the list using count().
g. Add an element to the end of the list using append().
h. Insert an element at a specific index using insert().
24
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
25
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
Tuple
A tuple in Python is an ordered (you can access them by their index), immutable collection of
items. Tuples are like lists, but they cannot be changed (i.e., they are immutable). Tuples are useful
when you want to store a fixed set of values and ensure that they remain constant throughout the
program. Tuples are created by placing values inside parentheses () separated by commas.
Syntax
Empty tuple
empty_tuple = ()
Tuple Slicing
# Slicing a tuple
numbers = (1, 2, 3, 4, 5, 6)
print(numbers[1:4]) # Output: (2, 3, 4)
print(numbers[:3]) # Output: (1, 2, 3)
print(numbers[3:]) # Output: (4, 5, 6)
print(numbers[::2]) # Output: (1, 3, 5)
26
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
Concatenation
You can combine tuples using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)
also check this
combined_tuple[0] #1-D
combined_tuple[1] #1-D
Repetition
Use the * operator to repeat a tuple multiple time.
numbers = (1, 2, 3)
repeated_tuple = numbers * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
In operator
Check if an element is in a tuple with in and not in.
fruits = ("apple", "banana", "cherry")
print("apple" in fruits) # Output: True
print("orange" not in fruits) # Output: True
Built-in functions
Function Description Example
len(tuple) Returns the number of len((1, 2, 3)) → 3
elements in the tuple.
max(tuple) Returns the maximum max((1, 2, 3)) → 3
element in a tuple (numbers
only).
27
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
Unpacking Tuples
Tuples support unpacking, which lets you assign the elements of a tuple to multiple variables in a
single line.
# Tuple unpacking
point = (1, 2, 3)
x, y, z = point
print(x) # Output: 1
print(y) # Output: 2
print(z) # Output: 3
Tuple in-operator
tup=(1,2,3)
for i in tup:
print(i)
also try these functions
*dir(tup), help()
28
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
Set
In Python, a set is an unordered and mutable collection of unique items. Sets are useful when you
want to store items without duplicates, such as in membership tests or performing set operations
like union, intersection, and difference.
Syntax
Sets are created using curly braces {} or the set() function.
Empty set
empty_set = set()
*Note: To create an empty set, you must use set() instead of {}, as {} creates an empty dictionary.
Adding an item
Use add() to add a single item to a set.
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits) # Output: {'apple', 'banana', 'cherry'}
Removing an item
Use remove() to remove a specific item (raises an error if the item doesn’t exist), or discard() to
remove without error.
29
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
Clearing tuple
Use clear() to empty a set.
fruits.clear()
print(fruits) # Output: set()
Set Operations
Operation Description Example
set.union(other_set) or | Combines all unique {1, 2, 3} | {2, 3, 4}→{1, 2,
elements from both sets. 3, 4}
set.intersection(other_set) or & Returns only elements {1, 2, 3} & {2, 3, 4} → {2,
present in both sets. 3}
set.difference(other_set) or - Returns elements present in {1, 2, 3} - {2, 3} → {1}
the first set but not in the
second.
set.symmetric_difference(other_set) Returns elements in either {1, 2, 3} ^ {2, 3, 4} → {1,
or ^ set but not both. 4}
30
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
set.issubset(other_set) or <= Checks if one set is a subset of {1, 2} <= {1, 2, 3} → True
another.
set1.issuperset(set2) Checks if one set is a superset {1, 2, 3} >= {1, 2} → True
of another.
set1.isdisjoint(set2) Checks if two sets have no {1, 2}.isdisjoint({3, 4}) →
elements in common. True
Set in-operator
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
31
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
32
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary
Let’s practice
Task
Tuple
1. Define a tuple with elements of different data types (e.g., integers, strings, floats). Access
the first, middle, and last elements of a tuple using indexing.
2. Create two tuples and concatenate them to form a new tuple.
3. Slice a tuple to get specific portions (first 3 elements, last 3 elements, or every second
element).
4. Use the in keyword to check if a particular element exists within a tuple.
5. Convert a tuple to a list, modify the list (e.g., add or remove an element), and convert it
back to a tuple.
6. Unpack elements from a tuple into individual variables (e.g., a, b, c = (1, 2, 3)).
7. Define a nested tuple (e.g., (1, (2, 3), 4)) and unpack it into individual variables.
8. Create a tuple of integers and sort it by converting it to a list, sorting it, and converting it
back to a tuple.
9. Write a function that takes a tuple as an argument, performs some operation (e.g., summing
the elements), and returns a result.
10. Create a function that returns multiple values as a tuple, such as (max_value, min_value).
Set
1. Create a set with a few elements of different data types (e.g., integers, strings, floats).Use
the .add() method to add a new element to a set. Use the .remove() or .discard() methods
to remove an element from a set.
2. Create two sets and find their intersection using both the & operator and .intersection()
method.
3. Create two sets and check if one is a subset of the other using .issubset() and if one is a
superset of the other using .issuperset().
4. Given a list of elements, convert it into a set to remove duplicates, then convert it back to
a list.
5. Given two lists, use sets to find the elements that are unique to each list.
6. Create a tuple with duplicate values, convert it into a set to remove duplicates, and print
the unique values.
7. Write a function that takes a word as input, converts it to a set, and returns True if it contains
all vowels (a, e, i, o, u) and False otherwise.
33