1.b.sequence
1.b.sequence
A sequence in Python is an ordered collection of items that can be indexed and sliced. Python provides four
built-in sequence types:
1. String (str)
A string is a collection of characters enclosed in single ('), double ("), or triple quotes (''' or """ """).
Creating Strings
str1 = 'Hello' # Single quotes
str2 = "Python" # Double quotes
str3 = '''Welcome''' # Triple quotes (also used for multi-line strings)
Output:
String Operations
text = "Python"
# Accessing characters
print(text[0]) # Output: P (first character)
print(text[-1]) # Output: n (last character)
# Slicing
print(text[0:3]) # Output: Pyt (first 3 characters)
# String Concatenation
print("Hello " + "World") # Output: Hello World
# String Repetition
print("Python! " * 3) # Output: Python! Python! Python!
# String Length
print(len(text)) # Output: 6
2. List (list)
A list is a collection of ordered, mutable (changeable) elements. It can store different data types.
Creating Lists
fruits = ["apple", "banana", "cherry"]
numbers = [10, 20, 30, 40]
mixed = [1, "hello", 3.5, True]
print(fruits)
print(numbers)
print(mixed)
List Operations
# Accessing Elements
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry
# Slicing
print(fruits[1:3]) # Output: ['banana', 'cherry']
# Modifying a List
fruits[1] = "blueberry" # Changing an element
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
# Adding Elements
fruits.append("orange") # Adds at the end
print(fruits) # ['apple', 'blueberry', 'cherry', 'orange']
# Removing Elements
fruits.remove("cherry") # Removes specific element
print(fruits)
# Length of List
print(len(fruits)) # Output: 3
3. Tuple (tuple)
A tuple is similar to a list but immutable (cannot be changed).
Creating Tuples
numbers = (10, 20, 30, 40)
fruits = ("apple", "banana", "cherry")
print(numbers)
print(fruits)
Tuple Operations
# Accessing Elements
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry
# Slicing
print(fruits[1:3]) # Output: ('banana', 'cherry')
# Length of Tuple
print(len(fruits)) # Output: 3
Tuple Immutability
# This will cause an error because tuples cannot be changed
# fruits[1] = "blueberry"
4. Range (range)
A range represents a sequence of numbers.
Creating Ranges
r1 = range(5) # 0 to 4
r2 = range(2, 10) # 2 to 9
r3 = range(1, 10, 2) # 1 to 9 with step 2
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print("Reversed List:", numbers) # Output: [5, 4, 3, 2, 1]
Summary
Sequence Type Mutable? Indexed? Allows Duplicate Values?
String (str) No Yes Yes
List (list) Yes Yes Yes
Tuple (tuple) No Yes Yes
Range (range) No Yes No