What are Sequences?
In Python, a sequence is an ordered collection of items. Each item in a sequence is called an element, and these elements are assigned an index (position) starting from zero. This means you can access individual elements using their index.
Common Sequence Types
Python has several built-in sequence types. Here are the most important ones:
Strings:
An ordered sequence of characters.
Example: name = "Alice"
Lists:
An ordered collection of items, which can be of different data types.
Mutable: You can change, add, or remove elements after creation.
Example: numbers = [1, 5, -2, 8]
Tuples:
An ordered collection of items, similar to lists.
Immutable: You cannot change the elements after creation.
Example: coordinates = (10, 20)
Ranges:
A sequence of numbers generated by the range() function. Useful for iterations.
Example: numbers = range(1, 6) # Represents numbers 1, 2, 3, 4, 5
Why Sequences Matter
Structured Data: Sequences let you organize data in a meaningful way, essential for solving problems and building applications.
Iteration: They can be easily iterated over using loops (like for loops) to process their elements one by one.
Slicing: You can extract specific sub-sequences (portions of a sequence) using slicing notation like my_sequence[start:end].
Lists: The Mutable Workhorses
Lists are one of the most fundamental and versatile data structures in Python. Here's why they're so important:
Ordered: Lists maintain the order in which you insert elements. This is crucial when the sequence of items matters.
Mutable: You can change the contents of a list even after it's created. You can add, remove, and modify elements at will.
Heterogeneous: Lists can hold elements of different data types. You can store integers, strings, Booleans, even other lists within a single list!
Creating Lists
Square Brackets: The most common way:
Python
numbers = [1, 5, 20, -8]
shopping_items = ["bread", "eggs", "cheese"]list() Constructor: Useful for converting other iterables:
Python
coordinates_tuple = (5, 12)
coordinates_list = list(coordinates_tuple)
Key Operations
Accessing Elements (Indexing):
Python
numbers = [10, 20, 30]
first_number = numbers[0] # 10
second_number = numbers[1] # 20Slicing: Extracting sub-lists
Python
middle_elements = numbers[1:3] # [20, 30]Adding Elements:
append(): Adds a single element to the end.
extend(): Adds multiple elements from another iterable.
insert() : Inserts an element at a specific position
Removing Elements:
remove(): Removes the first occurrence of a value.
pop(): Removes and returns the element at a specific index (or the last one by default).
del: Deletes an element by its index.
Checking Membership:
Python
if "milk" in shopping_items:
print("Milk is on the list")Iteration (Looping):
Python
for number in numbers:
print(number * 2)
Practical Example
Python
tasks = ["Write report", "Send emails", "Attend meeting"]
# Adding a new task
tasks.append("Learn Flask")
# Marking a task as done
completed_task = tasks.pop(0) # Removes and returns "Write report"
print("Today's Tasks:", tasks)
Why Choose Lists
Lists are fantastic when you need:
A collection of items where the order is important.
To modify the collection (add, remove, rearrange) after creation.
A structure to hold data of various types together.
Accessing and Modifying Elements
Indexing ([ ]) Access individual elements by their zero-based index.
Python
numbers = [1, 5, 3]
first_number = numbers[0] # first_number will be 1
numbers[2] = 10 # Changes the third element to 10Slicing ([:]) Extract a sub-list using the start:end:step notation. Remember, slicing creates a new list.
Python
letters = ['a', 'b', 'c', 'd']
middle_letters = letters[1:3] # middle_letters will be ['b', 'c']
Adding Elements
append(element) Adds a single element to the end of the list.
Python
shopping_list = ["bread", "milk"]
shopping_list.append("eggs")extend(iterable) Extends the list by adding elements from an iterable (like another list, tuple, or string).
Python
numbers = [1, 2, 3]
more_numbers = [4, 5]
numbers.extend(more_numbers) # numbers will become [1, 2, 3, 4, 5]insert(index, element) Inserts an element at a specific index, shifting other elements to the right.
Python
colors = ["red", "green", "blue"]
colors.insert(1, "yellow") # colors will become ["red", "yellow", "green", "blue"]
Removing Elements
remove(value) Removes the first occurrence of the specified value. Raises a ValueError if the value is not found.
Python
numbers = [1, 5, 2, 5]
numbers.remove(5) # removes the first '5'pop([index]) Removes and returns the element at the specified index (defaults to the last element if no index is given).
Python
colors = ["red", "green", "blue"]
last_color = colors.pop() # last_color will be "blue"del list_name[index] Deletes an element by its index. You can also use del to delete slices.
Other Important Operations
len(list_name) Returns the length (number of elements) of the list.
in and not in Check if an element exists in the list.
Python
if "apple" in fruits:
print("Found apple!")Iteration: Use for loops to process list elements.
Python
for color in colors:
print(color.upper())Sorting:
list_name.sort() Sorts the list in place (modifies the original list).
sorted(list_name) Returns a new sorted list without modifying the original.
Example Scenario
Python
todo_list = ["Buy groceries", "Study Python", "Water plants"]
todo_list.remove("Buy groceries") # Remove a task
new_task = "Call friend"
todo_list.append(new_task)
print("Updated To-Do List:")
for task in todo_list:
print(task)
Others
list.copy() Creates a shallow copy of the list.
Let's see an example:
Python
tasks = ["Finish project", "Call Sarah", "Learn Django"]
tasks.append("Buy groceries")
tasks.remove("Call Sarah")
print("To-Do List:")
for task in tasks:
print(task)
Example 1: Managing a Shopping List
Python
shopping_list = ["eggs", "bread", "milk", "bananas"]
# Add a new item
new_item = input("What would you like to add to the list? ")
shopping_list.append(new_item)
# Print the updated list
print("Your updated shopping list:")
for item in shopping_list:
print(item)
# Remove an item if you bought it
bought_item = input("Did you buy anything? If so, what? ")
if bought_item in shopping_list:
shopping_list.remove(bought_item)
print(f"Removed {bought_item} from the list.")
else:
print(f"{bought_item} is not on the list.")
Example 2: Calculating Numerical Statistics
Python
temperatures = [25.2, 28.5, 30.1, 26.7, 23.8]
# Calculate average temperature
average_temp = sum(temperatures) / len(temperatures)
print("Average temperature:", average_temp)
# Find minimum and maximum temperatures
min_temp = min(temperatures)
max_temp = max(temperatures)
print("Minimum temperature:", min_temp)
print("Maximum temperature:", max_temp)
Example 3: Word Frequency Analysis
Python
text = "This is a sample text for word frequency analysis.
This text contains some repeated words."
# Split the text into words and convert to lowercase
words = text.lower().split()
# Count the occurrences of each word
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# Print the words and their frequencies
for word, count in word_counts.items():
print(f"{word}: {count}")
Example 4: Sorting and Filtering
Python
students = [
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 78},
]
# Sort by grade (descending)
students.sort(key=lambda student: student["grade"], reverse=True)
print("Students sorted by grade:")
for student in students:
print(student)
# Filter students with grades above 80
passing_students = [student for student in students if student["grade"] > 80]
print("Passing students:")
for student in passing_students:
print(student)
Basic Concepts
Q: Explain what lists are in Python and how they differ from tuples.
A: Lists are ordered, mutable collections of items. They can hold elements of different data types. Tuples are similar to lists but are immutable, meaning their elements cannot be changed after creation.
Q: Describe how to create an empty list and a list with initial values.
A: You create an empty list using empty square brackets: my_list = []. To create a list with initial values, you place the values within the square brackets, separated by commas: numbers = [1, 5, 3, 8].
Q: How do you access elements in a list and update their values?
A: You access elements using zero-based indexing: first_item = my_list[0]. You update values directly by assigning to the index: my_list[2] = "new_value".
Operations and Functionality
Q: Explain the difference between list.append() and list.extend() methods.
A: append() adds a single element to the end of a list. extend() adds multiple elements from an iterable (like another list, string, or tuple) to the end of the list.
Q: What is the purpose of the list.remove() method and how does it differ from list.pop()?
A: remove() removes the first occurrence of a specified value from the list. pop() removes and returns the element at a given index (or the last element if no index is provided).
Q: How do you sort a list in ascending or descending order?
A: You use the list.sort() method to sort in ascending order: numbers.sort(). For descending order, you add the reverse=True argument: numbers.sort(reverse=True).
Scenarios and Problem-Solving
Q: Given a list of numbers, how would you find the second largest number?
A: One approach is to sort the list in descending order and then access the second element: numbers.sort(reverse=True); second_largest = numbers[1]. Alternatively, you can track the largest and second-largest numbers during a single iteration.
Q: How would you remove duplicate elements from a list?
A: One way is to create a new list and add only unique elements. Another efficient method is to convert the list to a set (which inherently stores unique elements) and then back to a list: unique_list = list(set(original_list)).
Q: Can you explain what list slicing is and give an example?
A: List slicing allows you to extract a sub-list using the notation list_name[start:end:step]. For example, middle_elements = my_list[1:4] would extract the elements from index 1 up to (but not including) index 4.
Functions for Adding/Inserting
list.append(x) Adds a single element (x) to the end of the list.
Python
numbers = [1, 2, 3]
numbers.append(4) # numbers becomes [1, 2, 3, 4]list.insert(index, x) Inserts an element (x) at a specific index within the list.
Python
colors = ["red", "green"]
colors.insert(1, "blue") # colors becomes ["red", "blue", "green"]list.extend(iterable) Appends all the elements from an iterable (list, tuple, etc.) to the end of the list.
Python
numbers = [1, 2]
more_numbers = [3, 4, 5]
numbers.extend(more_numbers) # numbers becomes [1, 2, 3, 4, 5]
Functions for Removing
list.remove(x) Removes the first occurrence of a value (x) from the list. Raises a ValueError if the value is not found.
Python
letters = ['a', 'b', 'c', 'b']
letters.remove('b') # letters becomes ['a', 'c', 'b']list.pop([index]) Removes and returns the element at a given index (defaults to the last element if no index is given).
Python
colors = ["red", "green", "blue"]
last_color = colors.pop() # last_color becomes "blue"list.clear() Removes all elements from the list, making it empty.
Python
my_list = [1, 2, 3]
my_list.clear() # my_list becomes []
Information and Searching
list.index(x) Returns the index of the first occurrence of a value (x) in the list. Raises a ValueError if not found.
Python
fruits = ["apple", "banana", "orange"]
banana_index = fruits.index("banana")list.count(x) Returns the number of times a value (x) appears in the list.
Python
numbers = [1, 5, 1, 3, 1]
count_of_1 = numbers.count(1) # count_of_1 becomes 3
Sorting and Reversing
list.sort() Sorts the elements of the list in ascending order (modifies the list in-place). Optionally takes reverse=True for descending order.
Python
numbers = [5, 2, 9, 1]
numbers.sort() # numbers becomes [1, 2, 5, 9]list.reverse() Reverses the order of elements in the list (modifies the list in-place).
Python
colors = ["red", "green", "blue"]
colors.reverse() # colors becomes ["blue", "green", "red"]
Others
list.copy() Creates a shallow copy of the list.
Let's see an example:
Python
tasks = ["Finish project", "Call Sarah", "Learn Django"]
tasks.append("Buy groceries")
tasks.remove("Call Sarah")
print("To-Do List:")
for task in tasks:
print(task)
What are Sequences? And Lists? In Python¶
list1 = [1,2,3,4,5]
print(list1)
[1, 2, 3, 4, 5]
list2=[1,'venkat',2,'kumar',3,True]
list2
[1, 'venkat', 2, 'kumar', 3, True]
list2[1]
'venkat'
list2[5]
True
list2[1:2]
['venkat']
list2[2:3]
[2]
list2=[1,'venkat',2,'kumar',3,True ,12,'venkaet',24,'kumdddar',44,False]
list2[2:3]
[2]
list2[2:6:1]
[2, 'kumar', 3, True]
list2
[1, 'venkat', 2, 'kumar', 3, True, 12, 'venkaet', 24, 'kumdddar', 44, False]
list2[5]
True
list2[3:7]
['kumar', 3, True, 12]
list2[2:9]
[2, 'kumar', 3, True, 12, 'venkaet', 24]
list2[2:9:3]
[2, True, 24]
list2
[1, 'venkat', 2, 'kumar', 3, True, 12, 'venkaet', 24, 'kumdddar', 44, False]
list2[1]='Ram'
list2
[1, 'Ram', 2, 'kumar', 3, True, 12, 'venkaet', 24, 'kumdddar', 44, False]
list2.append("mahesh")
list2
[1, 'Ram', 2, 'kumar', 3, True, 12, 'venkaet', 24, 'kumdddar', 44, False, 'mahesh']
print(list2)
[1, 'Ram', 2, 'kumar', 3, True, 12, 'venkaet', 24, 'kumdddar', 44, False, 'mahesh']
list2.append("mahesh",3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[41], line 1 ----> 1 list2.append("mahesh",3) TypeError: list.append() takes exactly one argument (2 given)
print(list2)
[1, 'Ram', 2, 'kumar', 3, True, 12, 'venkaet', 24, 'kumdddar', 44, False, 'mahesh']
print(list1)
[1, 2, 3, 4, 5]
list2..extend(list1)
Cell In[44], line 1 list2..extend(list1) ^ SyntaxError: invalid syntax
list2.extend(list1)
print(list2)
[1, 'Ram', 2, 'kumar', 3, True, 12, 'venkaet', 24, 'kumdddar', 44, False, 'mahesh', 1, 2, 3, 4, 5]
list1
[1, 2, 3, 4, 5]
list1.insert(3,10)
list1
[1, 2, 3, 10, 4, 5]
list1.remove(10)
list1
[1, 2, 3, 4, 5]
list3=[14,10,8,10,14,6,9,10,]
list3.remove(10)
list3
[14, 8, 10, 14, 6, 9, 10]
colors = ["red", "green", "blue","nblue","Nred", "Rgreen",]
#colors.pop()
colors
['red', 'green', 'blue']
colors.pop(0)
'red'
colors
['green', 'blue']
len(colors)
2
colors
['red', 'green', 'blue', 'nblue', 'Nred', 'Rgreen']
if "kblue" in colors:
print("Found nblue!")
list3
[14, 8, 10, 14, 6, 9, 10]
sorted(list3)
[6, 8, 9, 10, 10, 14, 14]
list3
[14, 8, 10, 14, 6, 9, 10]
list3.sort()
list3
[6, 8, 9, 10, 10, 14, 14]
todo_list = ["Buy groceries", "Study Python", "Water plants"]
todo_list.remove("Buy groceries") # Remove a task
new_task = "Call friend"
todo_list.append(new_task)
print("Updated To-Do List:")
for task in todo_list:
print(task)
Updated To-Do List: Study Python Water plants Call friend
for n in list3:
print(n)
6 8 9 10 10 14 14
list3.copy(k)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[79], line 1 ----> 1 list3.copy(k) NameError: name 'k' is not defined
list3=[14,10,8,10,14,6,9,10,]
sorted(list3)
[6, 8, 9, 10, 10, 10, 14, 14]
list3
[14, 10, 8, 10, 14, 6, 9, 10]
list3copy = list3.copy()
list3copy
[14, 10, 8, 10, 14, 6, 9, 10]
list3.sort()
list3
[6, 8, 9, 10, 10, 10, 14, 14]
list3 = list3copy.copy()
list3
[14, 10, 8, 10, 14, 6, 9, 10]
shopping_list = ["eggs", "bread", "milk", "bananas"]
# Add a new item
new_item = input("What would you like to add to the list? ")
shopping_list.append(new_item)
# Print the updated list
print("Your updated shopping list:")
for item in shopping_list:
print(item)
# Remove an item if you bought it
bought_item = input("Did you buy anything? If so, what? ")
if bought_item in shopping_list:
shopping_list.remove(bought_item)
print(f"Removed {bought_item} from the list.")
else:
print(f"{bought_item} is not on the list.")
What would you like to add to the list? coffe Your updated shopping list: eggs bread milk bananas coffe Did you buy anything? If so, what? bread Removed bread from the list.
shopping_list
['eggs', 'milk', 'bananas', 'coffe']
temperatures = [25.2, 28.5, 30.1, 26.7, 23.8]
sum(temperatures)
134.3
max(temperatures)
30.1
avg(temperatures)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[94], line 1 ----> 1 avg(temperatures) NameError: name 'avg' is not defined
text = "This is a sample text for word frequency analysis. This text contains some repeated words."
text.lower()
'this is a sample text for word frequency analysis. this text contains some repeated words.'
text.lower().split()
['this', 'is', 'a', 'sample', 'text', 'for', 'word', 'frequency', 'analysis.', 'this', 'text', 'contains', 'some', 'repeated', 'words.']
k=text.lower().split()
k
['this', 'is', 'a', 'sample', 'text', 'for', 'word', 'frequency', 'analysis.', 'this', 'text', 'contains', 'some', 'repeated', 'words.']
text = "This is a sample text for venkat vlr vlr word frequency analysis.This text contains some repeated words."
# Split the text into words and convert to lowercase
words = text.lower().split()
# Count the occurrences of each word
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# Print the words and their frequencies
for word, count in word_counts.items():
print(f"{word}: {count}")
this: 1 is: 1 a: 1 sample: 1 text: 2 for: 1 venkat: 1 vlr: 2 word: 1 frequency: 1 analysis.this: 1 contains: 1 some: 1 repeated: 1 words.: 1
my_list = []
my_list
[]
list3
[14, 10, 8, 10, 14, 6, 9, 10]
list3.sort (reverse=True)
list3
[14, 14, 10, 10, 10, 9, 8, 6]
#colors = ["red", "green", "blue"]
colors.reverse() # colors becomes ["blue", "green", "red"]
colors
['Rgreen', 'Nred', 'nblue', 'blue', 'green', 'red']
my_list1 = [1, 2, 3]
my_list1.clear()
my_list1
[]
fruits = ["apple", "banana", "orange","banana","banana"]
banana_index = fruits.index("banana1")
banana_index
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[120], line 2 1 fruits = ["apple", "banana", "orange","banana","banana"] ----> 2 banana_index = fruits.index("banana1") 3 banana_index ValueError: 'banana1' is not in list
fruits.count("banana")
3
No comments:
Post a Comment
Note: only a member of this blog may post a comment.