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 [ ].
myList = ["abacab", 575, 24, 5, 6]
print(myList[0]) # Output: "abacab"
print(myList[1]) # Output: 575
for item in myList:
print(item)
myList.append(100) # Adds 100 at the end
myList.remove(24) # Removes the first occurrence of 24
numbers = [5, 2, 9, 1]
numbers.sort() # Sorts in ascending order
Append a single new element to a list. It may be another list.
>>> li = [1, 11, 3, 4, 5]
>>> li.append(‘a’) # Note the method syntax
>>> li
[1, 11, 3, 4, 5, ‘a’]
>>> li.insert(2, ‘i’)
>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]
Lists have many methods, including index, count, remove, reverse, sort
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of 1st occurrence
1
>>> li.count(‘b’) # number of occurrences
2
>>> li.remove(‘b’) # remove 1st occurrence
>>> li
[‘a’, ‘c’, ‘b’]
>>> li = [5, 2, 6, 8]
>>> li.reverse() # reverse the list *in place*
>>> li
[8, 6, 2, 5]
>>> li.sort() # sort the list *in place*
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
+ creates a fresh list with a new memory ref
extend operates on list li in place. extend takes a list as an argument. So multiple elements can be added using extend.
>>> li.extend([9, 8, 7])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7]
append takes a singleton as an argument.
>>> li.append([10, 11, 12])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
A tuple is similar to a list but immutable, meaning elements cannot be changed after assignment. Tuples are defined using parentheses ().
myTuple = ("apple", "banana", "cherry")
print(myTuple[1]) # Output: "banana"
for item in myTuple:
print(item)
print(len(myTuple)) # Output: 3
temp_list = list(myTuple)
temp_list.append("orange")
myTuple = tuple(temp_list)
>>> 1,
(1,)
Don't forget the comma! Without comma no tuple is created.
>>> (1)
1
A single element in a tuple or list is obtained using indexing in one of two ways.
Positive index: count from the left, starting with 0
Negative index: count from right, starting with –1
Range of indexes is possible that gives elements from 1st element including to the last index excludig
t = (23, 'abc', 4.56, "Home", 'def')
t[1] #points to ‘abc’
t[-3] #points to 4.56
t[1:4] #points to a new tuple (‘abc’, 4.56, "Home") that are at index 1, 2 and 3
t[1:-1] #points to new tuple (‘abc’, 4.56, "Home") that are at index, 1, 2, and 3
Omit first index to make copy starting from beginning of the container
t[:2] #gives (23, ‘abc’)
Omit second index to make copy starting at first index and going to end
t[2:] #gives (4.56, (2,3), ‘def’)
l2 = l1[:] # Makes a new independent copy
t = [1, 2, 4, 5]
3 in t # returns a False
(1, 2, 3) + (4, 5, 6) # gives (1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6] # gives [1, 2, 3, 4, 5, 6]
>>> "Hello" + " " + "World" #gives ‘Hello World’
(1, 2, 3) * 3 #gives (1, 2, 3, 1, 2, 3, 1, 2, 3)
[1, 2, 3] * 3 #gives [1, 2, 3, 1, 2, 3, 1, 2, 3]
“Hello” * 3 #gives ‘HelloHelloHello’
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14
Traceback (most recent call last):
File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment
You can’t change a tuple.
You can make a fresh tuple and assign its reference to a previously used name.
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
The immutability of tuples means they’re faster than lists.
Dictionary holds key-value pairs.
my_dictionary = {
'first_name': "Noor",
'last_name': "Muhammad",
'age': 36,
'my_ip': (192,168,1,225),}
There are useful functions to add, delete and find values in dictionary.
# Access the items:
print(my_dictionary.keys())
print(my_dictionary.items())
print(my_dictionary.values())
#len(my_dictionary): Number of items in dictionary.
print(len(my_dictionary))
# retuens 4
#my_dictionary[k]: Item of dictionary with key k.
print(my_dictionary['first_name'])
#my_dictionary[k]=x: Assign key k with value x. Change or add new
my_dictionary['city']='Lahore'
print(my_dictionary.items())
#del my_dictionary [k]: Delete item with key k.
del my_dictionary ['age']
print(my_dictionary.items())
#k in my_dictionary: Determine if dictionary has an item with key k.
print('ip' in my_dictionary)
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.
Lists slower but more powerful than tuples
Lists can be modified, and they have lots of handy operations and mehtods
Tuples are immutable and have fewer features
To convert between tuples and lists use the list() and tuple() functions:
li = list(tu)
tu = tuple(li)