Tutorial: Difference between Lists and Tuples¶
The following content and code excerpts have been derived from the following sources.- Python Tutorial from Tutorialspoint. https://www.tutorialspoint.com/python/
- How to Loop with indexes in Python. http://treyhunner.com/2016/04/how-to-loop-with-indexes-in-python/
- Python.org Tutorials. https://docs.python.org/2/tutorial/index.html
- Learnpython.org. https://www.learnpython.org
- Introductin to Python Programming https://github.com/jrjohansson/scientific-python-lectures/blob/master/Lecture-1-Introduction-to-Python-Programming.ipynb
- Iterating with Python Lambdas. https://caisbalderas.com/blog/iterating-with-python-lambdas/
- Proper way to copy lists. http://henry.precheur.org/python/copy_list.html
Creation and Assignment of Lists and Tuples¶
"Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end."
Lists are assigned using square brackets and values are separate with commas
Syntax for Lists in Python is [ . . . ]
Lists are assigned using square brackets and values are separate with commas
Syntax for Lists in Python is [ . . . ]
In [19]:
b = [1, 2, 3] #lists use square brackets for assignment
print(type(b))
print(b)
"Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference."
Tuples are assigned using rounded parantheses and values are separated with commas
Syntax for Lists in Python is ( . . . )
Tuples are assigned using rounded parantheses and values are separated with commas
Syntax for Lists in Python is ( . . . )
In [26]:
a = (1,2,3) #tuples use rounded parantheses for assignment
t = 'a','b','c' #Paranthesis are not compulsory to define tuples, but using paranthesis is recommended
print(type(a))
print(a)
print(type(t))
print(t)
Special Case for Tuples - Creating singleton or Empty tuples¶
"A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective."
In [44]:
empty = ()
singleton = 'hello', # <-- note trailing comma
print(len(empty))
print(type(empty))
print
print(len(singleton))
print(singleton)
print(type(singleton))
Lists can store numbers characters, strings or mixed set of data
In [21]:
a = ['x','y','z'] #Lists can store any characters
b =['abc','cdf','efg'] #lists can store strings
c = [1, 2, 5-1j, 'nepal',25, 'm'] #lists can store a mixed set of datatypes too
print(a)
print(b)
print(c)
In [23]:
a = [x,5,z] #characters must be defined inside quotation marks, otherwise it will be considered a variable
a #since x has not been assigned earlier, this will throw an error
Tuples can also store numbers, characters, strings or mixed set of data.
In [22]:
a = ('x','y','z') #tuples can store any characters
b =('abc','cdf','efg') #tuples can store strings
c = (1, 2, 'x', 1-2j) #tuples can store a mixed set of datatypes too
print(a)
print(b)
print(c)
In [24]:
a = (x,5,z) #characters must be defined inside quotation marks, otherwise it will be considered a variable
a #since x has not been assigned earlier, this will throw an error
Accessing items in Lists and Tuples¶
You recall values from lists and tuples in exactly the same way.
It is very important to note that the indexing in Lists and Tuples start from 0.
It is very important to note that the indexing in Lists and Tuples start from 0.
In [29]:
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester'] #list
months = ('January','February','March','April','May','June','July','August','September','October','November',' December') #tuple
print('The third cat is ' + cats[2])
print('The third month is '+ months[2])
It is possible to access elements of Lists and Tuples in a range. The range can be defined is defined using square brackets for bot lists and tuples.
Syntax: tuple_or_list_name[start:end:step]
Syntax: tuple_or_list_name[start:end:step]
In [35]:
print('The first 3 months are as follows:')
print(months[0:2:1]) #months is a tuple here
print('The first 3 cats are as follows:')
print(cats[0:2])#if the step value is not mentioned, the default step value is considered as 1
print
print(months[:])
#if the start value is not mentioned it refers to the begining of the list or the tuple
#if the end value if not mentioned it refers to the end of the list or the tuple
#if both are not mentioned it basically means the complete list or tuple
In the above examples, the 'slices' of lists and tuples that we have obtained can be understood as the subsets of the lists or the tuples. And the slices themselves are of the tupleType. Therefore, we can not concatenate the them with stringTypes.
In [43]:
print(months[0:11:2])
print(type(months[0:11:2]))
print #this line is for printing an empty line
print(cats[:3])
print(type(cats[:3]))
print('') #this line is also for printing an empty line
#the following code will generate error as we are trying to concatenate stringType with TupleType
print('The odd months are '+ months[0:11:2])
Actions on Lists and Tuples¶
The major difference between Tuples and Lists is that Tuples are immutable while Lists are mutable.¶
This basically means that the elements in Tuples cannot be changed. And thus the elements in tuples CANNOT be updated or removed. Hence, there are no actions that are associated with the data type Tuples.
However the tuple type objects can call two functions - COUNT and INDEX.
However the tuple type objects can call two functions - COUNT and INDEX.
In [47]:
vowels = ('a', 'e', 'i', 'o', 'i', 'o', 'e', 'i', 'u') # vowels tuple
count = vowels.count('i') # count element 'i'
print('i occurs the following times in the tuple: ', count)
print
count = vowels.count('p') # # count element 'p'
print('p occurs the following times in the tuple: ', count)
In [48]:
index = vowels.index('e') #indexing element e
print('The index of e:', index)
print
index = vowels.index('i') #indexing element i
print('The index of i:', index)
# only the first index of the element is printed
It is also not possible to delete or remove an element from a tuple. However, del statement can be used to remove or delete an entire tuple.
In [50]:
tup = ('physics', 'chemistry', 1997, 2000)
print tup
del tup
print "After deleting tup : "
print tup #throws an error because no such tuple exists
Actions on List Type Objects¶
As mentioned earlier, Lists are mutable. This means that the elements of a List type object can be changed or elements can be added and deleted.
Append() and Insert()¶
The append() method adds a single item to the existing list. It doesn't return a new list; rather it modifies the original list. You can also addThe syntax of append() method is:
list.append(item)
In [52]:
animal = ['cat', 'dog', 'rabbit']
animal.append('tiger') # adding new element to the list
print('Updated animal list: ', animal) #Updated animal List
In [24]:
animal = ['cat', 'dog', 'rabbit']
wild_animal = ['tiger', 'fox']
animal.append(wild_animal) # adding wild_animal list to animal list
print('Updated animal list: ', animal)
print
print('It is important to note that the list wild_animal is added to the animal list as a single element.')
print('Only one element of type List has been added to the existing list')
We can insert items into lists using insert function.
In [27]:
animal.insert(2,'wildcat') #inserts wildcat at index 2
print('Updated animal list: ', animal)
Extend()¶
If in the above case, we want to add the elements of the list wild_animal to the existing animal list, then we have to use the extend() function. The extend() extends the list by adding all items of a list (passed as an argument) to the end. We can also add elements of a tuple or a set data type to an existing list.Syntax: list1.extend(list2)
In [58]:
# language list
language = ['French', 'English', 'German']
# another list of language
language1 = ['Spanish', 'Portuguese']
language.extend(language1)
# Extended List
print('Language List: ', language)
In [61]:
# language list
language = ['French', 'English', 'German']
# language tuple
language_tuple = ('Spanish', 'Portuguese')
# appending element of a tuple to an existing list
language.extend(language_tuple)
print('New Language List: ', language)
We can also add the elements of a list to anthor list by using the operator +=
In [63]:
a = [1, 2]
b = [3, 4]
a += b
print(a)
Insert()¶
The insert() method inserts the element to the list at the given index.Syntax: list.insert(index, element)
In [64]:
# vowel list
vowel = ['a', 'e', 'i', 'u']
# inserting element to list at 4th position
vowel.insert(3, 'o')
print('Updated List: ', vowel)
Remove()¶
The remove() method searches for the given element in the list and removes the first matching element.Sytax: list.remove(element)
In [67]:
animal = ['cat', 'dog', 'rabbit', 'guinea pig']
# 'rabbit' element is removed
animal.remove('rabbit')
#Updated Animal List
print('Updated animal list: ', animal)
print
animal1 = ['cat','dog','fox','dog','dog','cat']
animal1.remove('dog') #removing repititive elements from a list will remove only one of them
print('Updated animla1 list: ',animal1)
animal.remove('wildcat') #removing non existing element will cause error
print('Updated animal list: ',animal)
Pop()¶
The pop() method removes and returns the element at the given index (passed as an argument) from the list.Syntax: list.pop(index)
In [68]:
language = ['Python', 'Java', 'C++', 'French', 'C']
# Return value from pop()
# When 3 is passed
return_value = language.pop(3)
print('Return Value: ', return_value)
# Updated List
print('Updated List: ', language)
In [69]:
# programming language list
language = ['Python', 'Java', 'C++', 'Ruby', 'C']
# When index is not passed
print('When index is not passed:')
print('Return Value: ', language.pop())
print('Updated List: ', language)
# When -1 is passed
# Pops Last Element
print('\nWhen -1 is passed:')
print('Return Value: ', language.pop(-1))
print('Updated List: ', language)
# When -3 is passed
# Pops Third Last Element
print('\nWhen -3 is passed:')
print('Return Value: ', language.pop(-3))
print('Updated List: ', language)
In [70]:
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)
# List Reverse
os.reverse()
# updated list
print('Updated List:', os)
Reversing a lis using SLICING operators
Syntax: reversed_list = os[start:stop:step]
Syntax: reversed_list = os[start:stop:step]
In [73]:
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)
reversed_list = os[::-1]
print('Updated List:', reversed_list)
Printing Elements in Reversed Order
reveresed() is a function that allows accessing a list in reverse order
reveresed() is a function that allows accessing a list in reverse order
In [72]:
for o in reversed(os):
print(o)
sort(), copy() and clear()¶
Sort() can be used to sort the elements of a list.Syntax: list.sort(key=..., reverse=...)
In [76]:
vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort()
print('Sorted list:', vowels) #sorts the ASCII values
vowels.sort(reverse=True) #sort in reverse order
print('Sorted list (in Descending):', vowels)
Copy() can be used to copy one list to another and clear() can be used to remove all items from a list.
In [82]:
old_list = ['cat', 0, 6.7]
new_list = old_list.copy() #NEED TO UNDERSTAND THIS ERROR (NOTE FOR SELF)
new_list.append('dog')
#same thing can be achieved using the = operator
newer_list = old_list
# Printing new and old list
print(new_list)
print(newer_list)
Clear() can be used to remove all elements from the list
In [83]:
print(len(old_list.clear()))
print(old_list)
For Loop with Lists and Tuples¶
A for loop is used to run through the elements of a list or a tuple.
In [19]:
#Iterationg through a list using for Loop
shopping = ['bread','jam','butter']
for item in shopping:
print(item + ' has been added to the cart')
print
#Iterating through a tuple using for loop
days_in_a_week = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
for a_day in days_in_a_week:
print (a_day)
In [21]:
#Iterating through a List without a name that is defined inside the loop only
for num in [1,2,3,4,5]:
print ('The square of '+ str(num) + ' is '+ str(num**2))
print
#Iterating through a tuple without a name that is defined inside the loop only
for even_num in (2,4,6,8,10):
print ('The half of '+ str(even_num) + ' is '+ str(even_num/2))
We can also loop using the indices of the Lists
In [23]:
names = ['Adam','Eve','Jack','Jill']
i=0
for i in range (0, 4):
print (names[i])
i = i + 1
colors = ('red','black','green','blue')
k = 0
for k in range (0,4):
print (colors[k])
If Statement with Lists and Tuples¶
We can compare the elements of lists and tuples using their indices with IF Statement.
In [28]:
shopping_list = ['bread','jam','marmite']
for item in shopping_list:
if item == 'marmite':
print('Yuck!!')
else:
print('Yum!!!')
In [30]:
if shopping_list[0] == 'bread': #using index to compare the element inside IF statement
print('Bread is awesome')
else:
print('Jam and Marmite are awesome as well! Oh wait, Marmite is not.')
The usage of If Statement and Tuples is similar.
In [31]:
weekdays = ('Monday','Tuesday','Wednesday','Thursday','Friday')
for day in weekdays:
if day == 'Friday':
print('Thank God!')
else:
print('Waiting for Friday!')
While Loops with Lists and Tuples¶
If we wanted to mimic the behavior of our traditional C-style for loop in Python, we could use a while loop.
In [32]:
colors = ["red", "green", "blue", "purple"]
i = 0
while i < len(colors):
print(colors[i])
i += 1
In [33]:
colors = ["red", "green", "blue", "purple"]
while i in range(len(colors)):
print(colors[i])
In [37]:
#when we have to use indices.. same format can be applied to for loop as well
presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams", "Jackson"]
i =0
while i in range(len(presidents)):
print("President {}: {}".format(i + 1, presidents[i]))
i+=1
MORE on Looping with Lists and Tuples¶
Python’s built-in enumerate function allows us to loop over a list and retrieve both the index and the value of each item in the list. The enumerate function gives us an iterable where each element is a tuple that contains the index of the item and the original item value.This function is meant for solving the task of:
- Accessing each item in a list (or another iterable)
- Also getting the index of each item accessed
In [38]:
colors = ["red", "green", "blue", "purple"]
ratios = [0.2, 0.3, 0.1, 0.4]
for i, color in enumerate(colors): #works in the same way with tuples
ratio = ratios[i]
print("{}% {}".format(ratio * 100, color))
We can use zip function to iterate over mulitple lists at the same time
In [42]:
colors = ("red", "green", "blue", "purple")
ratios = (0.2, 0.3, 0.1, 0.4)
for color, ratio in zip(colors, ratios):#works in the same way for lists
print("{}% {}".format(ratio * 100, color))
Lists and Tuples with Lambda¶
In [46]:
x = [2, 3, 4, 5, 6]
y = []
for v in x:
y += [v * 5]
print x
print y
Above result can be obtained using lamda operator and the map function
In [48]:
y = map(lambda v : v * 5, x)
print y
In [52]:
x = (1,2,3,4,5) #TUPLE
y = map(lambda v : v * 5, x)
print y #same action on a tuple yields a List as the map function returns a List
More complex operations can be achieved using Lambdas
In [56]:
x = [2, 3, 4, 5, 6]
y = map(lambda v : v * 5, filter(lambda u : u % 2, x))
print (filter(lambda u: u % 2, x))
#select the odd numbers number from the list x, and then multiply it by 5
print y