Skip to main content

Tutorial 1 - Lists and Tuples

Lists and Tuples in Python

Tutorial: Difference between Lists and Tuples

The following content and code excerpts have been derived from the following sources.
  1. Python Tutorial from Tutorialspoint. https://www.tutorialspoint.com/python/
  2. How to Loop with indexes in Python. http://treyhunner.com/2016/04/how-to-loop-with-indexes-in-python/
  3. Python.org Tutorials. https://docs.python.org/2/tutorial/index.html
  4. Learnpython.org. https://www.learnpython.org
  5. Introductin to Python Programming https://github.com/jrjohansson/scientific-python-lectures/blob/master/Lecture-1-Introduction-to-Python-Programming.ipynb
  6. Iterating with Python Lambdas. https://caisbalderas.com/blog/iterating-with-python-lambdas/
  7. 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 [ . . . ]
In [19]:
b = [1, 2, 3] #lists use square brackets for assignment

print(type(b))
print(b)
<type 'list'>
[1, 2, 3]
"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 ( . . . )
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)
<type 'tuple'>
(1, 2, 3)
<type 'tuple'>
('a', 'b', 'c')

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))
0
<type 'tuple'>

1
('hello',)
<type 'tuple'>
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)
['x', 'y', 'z']
['abc', 'cdf', 'efg']
[1, 2, (5-1j), 'nepal', 25, 'm']
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

NameErrorTraceback (most recent call last)
<ipython-input-23-f8e48035200e> in <module>()
----> 1 a = [x,5,z] #characters must be defined inside quotation marks, otherwise it will be considered a variable
      2 a #since x has not been assigned earlier, this will throw an error

NameError: name 'x' is not defined
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)
('x', 'y', 'z')
('abc', 'cdf', 'efg')
(1, 2, 'x', (1-2j))
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

NameErrorTraceback (most recent call last)
<ipython-input-24-6a86548650d9> in <module>()
----> 1 a = (x,5,z) #characters must be defined inside quotation marks, otherwise it will be considered a variable
      2 a #since x has not been assigned earlier, this will throw an error

NameError: name 'x' is not defined

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.
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])
The third cat is Kitty
The third month is March
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]
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
The first 3 months are as follows:
('January', 'February')
The first 3 cats are as follows:
['Tom', 'Snappy']

('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', '  December')
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])
('January', 'March', 'May', 'July', 'September', 'November')
<type 'tuple'>

['Tom', 'Snappy', 'Kitty']
<type 'list'>


TypeErrorTraceback (most recent call last)
<ipython-input-43-866a47ae44e3> in <module>()
      6 print('') #this line is also for printing an empty line
      7 #the following code will generate error as we are trying to concatenate stringType with TupleType
----> 8 print('The odd months are '+ months[0:11:2])

TypeError: cannot concatenate 'str' and 'tuple' objects

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.
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)
('i occurs the following times in the tuple: ', 3)

('p occurs the following times in the tuple: ', 0)
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
('The index of e:', 1)

('The index of i:', 2)
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
('physics', 'chemistry', 1997, 2000)
After deleting tup : 

NameErrorTraceback (most recent call last)
<ipython-input-50-d77d02d08d83> in <module>()
      3 del tup
      4 print "After deleting tup : "
----> 5 print tup #throws an error because no such tuple exists

NameError: name 'tup' is not defined

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 add
The 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
('Updated animal list: ', ['cat', 'dog', 'rabbit', 'tiger'])
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')
('Updated animal list: ', ['cat', 'dog', 'rabbit', ['tiger', 'fox']])

It is important to note that the list wild_animal is added to the animal list as a single element.
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)
('Updated animal list: ', ['cat', 'dog', 'wildcat', 'wildcat', 'rabbit', ['tiger', 'fox']])
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)
('Language List: ', ['French', 'English', 'German', 'Spanish', 'Portuguese'])
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)
('New Language List: ', ['French', 'English', 'German', 'Spanish', 'Portuguese'])
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)
[1, 2, 3, 4]
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)
('Updated List: ', ['a', 'e', 'i', 'o', 'u'])
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)
('Updated animal list: ', ['cat', 'dog', 'guinea pig'])

('Update animla1 list: ', ['cat', 'fox', 'dog', 'dog', 'cat'])

ValueErrorTraceback (most recent call last)
<ipython-input-67-c7a3b9d93172> in <module>()
     12 print('Update animla1 list: ',animal1)
     13 
---> 14 animal.remove('wildcat') #removing non existing element will cause error
     15 print('Updated animal list: ',animal)
     16 

ValueError: list.remove(x): x not in list
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)
('Return Value: ', 'French')
('Updated List: ', ['Python', 'Java', 'C++', 'C'])
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)
When index is not passed:
('Return Value: ', 'C')
('Updated List: ', ['Python', 'Java', 'C++', 'Ruby'])

When -1 is passed:
('Return Value: ', 'Ruby')
('Updated List: ', ['Python', 'Java', 'C++'])

When -3 is passed:
('Return Value: ', 'Python')
('Updated List: ', ['Java', 'C++'])
Reverse()
The reverse() method reverses the elements of a given list.
Syntax: list.reverse()
In [70]:
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)

# List Reverse
os.reverse()

# updated list
print('Updated List:', os)
('Original List:', ['Windows', 'macOS', 'Linux'])
('Updated List:', ['Linux', 'macOS', 'Windows'])
Reversing a lis using SLICING operators
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)
('Original List:', ['Windows', 'macOS', 'Linux'])
('Updated List:', ['Linux', 'macOS', 'Windows'])
Printing Elements in Reversed Order
reveresed() is a function that allows accessing a list in reverse order
In [72]:
for o in reversed(os):
    print(o)
Linux
macOS
Windows
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)
('Sorted list:', ['a', 'e', 'i', 'o', 'u'])
('Sorted list (in Descending):', ['u', 'o', 'i', 'e', 'a'])
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)

AttributeErrorTraceback (most recent call last)
<ipython-input-82-88bfa74e3e4f> in <module>()
      1 old_list = ['cat', 0, 6.7]
----> 2 new_list = old_list.copy()
      3 new_list.append('dog')
      4 
      5 #same thing can be achieved using the = operator

AttributeError: 'list' object has no attribute 'copy'
Clear() can be used to remove all elements from the list
In [83]:
print(len(old_list.clear()))
print(old_list)

AttributeErrorTraceback (most recent call last)
<ipython-input-83-59af470159c4> in <module>()
----> 1 print(len(old_list.clear()))
      2 print(old_list)

AttributeError: 'list' object has no attribute 'clear'

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)
bread has been added to the cart
jam has been added to the cart
butter has been added to the cart

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
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))
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25

The half of 2 is 1
The half of 4 is 2
The half of 6 is 3
The half of 8 is 4
The half of 10 is 5
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])
Adam
Eve
Jack
Jill
red
black
green
blue

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!!!')
Yum!!!
Yum!!!
Yuck!!
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.')
Bread is awesome
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!')
Waiting for Friday!
Waiting for Friday!
Waiting for Friday!
Waiting for Friday!
Thank God!

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
red
green
blue
purple
In [33]:
colors = ["red", "green", "blue", "purple"]
while i in range(len(colors)):
    print(colors[i])
red
green
blue
purple
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
President 1: Washington
President 2: Adams
President 3: Jefferson
President 4: Madison
President 5: Monroe
President 6: Adams
President 7: Jackson

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:
  1. Accessing each item in a list (or another iterable)
  2. 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))
20.0% red
30.0% green
10.0% blue
40.0% purple
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))
20.0% red
30.0% green
10.0% blue
40.0% purple

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
[2, 3, 4, 5, 6]
[10, 15, 20, 25, 30]
Above result can be obtained using lamda operator and the map function
In [48]:
y = map(lambda v : v * 5, x)
print y
[10, 15, 20, 25, 30]
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
[5, 10, 15, 20, 25]
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
[3, 5]
[15, 25]

Popular posts from this blog

Tutorial 6 - Statistics and Probability

Statistics and Probability with Python HW 6 Statistics and probability homework ¶ Complete homework notebook in a homework directory with your name and zip up the homework directory and submit it to our class blackboard/elearn site. Complete all the parts 6.1 to 6.5 for score of 3. Investigate plotting, linearegression, or complex matrix manipulation to get a score of 4 or cover two additional investigations for a score of 5. 6.1 Coin flipping ¶ 6.1.1 ¶ Write a function, flip_sum, which generates $n$ random coin flips from a fair coin and then returns the number of heads. A fair coin is defined to be a coin where $P($heads$)=\frac{1}{2}$ The output type should be a numpy integer, hint: use random.rand() In [4]: import numpy as np import random """def random_flip(): return random.choice(["H", "T"]) def flip_sum(n): heads_count = 0 ...

Tutorial 5 - Matplotlib

Matplotlib Tutorial In [13]: % matplotlib inline import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # Setting some Pandas options pd . set_option ( 'display.notebook_repr_html' , False ) pd . set_option ( 'display.max_columns' , 25 ) pd . set_option ( 'display.max_rows' , 25 ) Homework 4 ¶ Couple of reference site: http://matplotlib.org/examples/pylab_examples/ http://docs.scipy.org/doc/numpy/ Homework 4.1 ¶ 4.1.a Create a figure with two subplots in a row. One shows a sine wave of x from with x = 0 ... 2*pi the other shows the tagent of x with the same range. Label the figures. Should look something like: We can follow the following steps to get the required graphs showing sine and tangents of x: Create a numpy array x with values from 0 to 2*pi with 0.001 as step value Set the height and w...

Domain Research - Stock Market Prediction

Hi, as part of my research on a domain of Big Data implementation, I chose Stock Market Prediction. Here I present to you the things that I have learned during my research in the domain. Can stock market be predicted? Early researches on stock market prediction revolved around whether it could be predicted. One of such researches suggested that “short term stock price movements were governed by the  random walk hypothesis  and thus were unpredictable”. Another stated that “the stock price reflected completed market information and the market behaved efficiently so that instantaneous price corrections to equilibrium would make stock prediction useless.” In simple terms, the researches inferred that since the market was affected by a lot of factors which were random predicting the stock market is almost impossible. However, researches carried out later (Brown & Jennings 1998; Abarbanel & Bushee 1998) made use of ...