To understand the basic functions of lists and tuples in Python and how to manipulate them effectively.
Lists and tuples are fundamental data structures in Python used for storing collections of data. Lists are mutable (modifiable), while tuples are immutable (cannot be modified after creation).
A list is an ordered collection that allows duplicates and can contain elements of different data types. Lists are defined using square brackets [].
Basic List Operations:
Creating a list:
myList = ["abacab", 575, 24, 5, 6]
Accessing elements using indexing:
print(myList[0]) # Output: "abacab"
print(myList[1]) # Output: 575
Iterating through a list:
for item in myList:
print(item)
Adding elements:
myList.append(100) # Adds 100 at the end
Removing elements:
myList.remove(24) # Removes the first occurrence of 24
Sorting a list:
numbers = [5, 2, 9, 1]
numbers.sort() # Sorts in ascending order
A tuple is similar to a list but immutable, meaning elements cannot be changed after assignment. Tuples are defined using parentheses ().
Basic Tuple Operations:
Creating a tuple:
myTuple = ("apple", "banana", "cherry")
Accessing elements using indexing:
print(myTuple[1]) # Output: "banana"
Iterating through a tuple:
for item in myTuple:
print(item)
Finding the length of a tuple:
print(len(myTuple)) # Output: 3
Converting a tuple to a list:
temp_list = list(myTuple)
temp_list.append("orange")
myTuple = tuple(temp_list)
Write a program that takes a list of numbers from the user and prints the sum.
Convert a given tuple into a list, add an element, and convert it back to a tuple.
Write a function that returns the maximum and minimum values from a given list.
Lists and tuples are essential data structures in Python. Understanding their basic operations allows for effective data storage and manipulation. Lists provide flexibility, while tuples offer performance advantages when immutability is required.