Datatypes to Data Structures
Week 2 – Lecture 1
Dr. Syed Imran Ali
By the End of Lecture
• Review Basic Data Types
• Built-in Containers
• Specialized Containers
Advanced Programming in Python 2
Data Types
• A data type defines the kind of value and the operations that can be
performed on it.
• In Python, everything is an object, and every object has a data type
(int, str, list, etc.).
• They answer “What is this value?”
x = 10 # type: int
y = "hello" # type: str
z = [1, 2, 3] # type: list
Advanced Programming in Python 3
Data Structures
• A data structure is a way of organizing and storing data so that it can
be used efficiently.
• It is more about design and organization, often built using data types.
• They answer “How is this data organized?”
• A list is a data structure that organizes elements in order
(sequence).
• A dictionary is a data structure that organizes data into key–value
mappings.
• A stack or queue can be implemented using a list or deque.
Advanced Programming in Python 4
Conceptual Relationship
In Python
• Data types are the building blocks.
• Data structures are arrangements/organizations built from
those types.
Analogy
• Data type = a kind of brick (e.g., clay brick, cement block).
• Data structure = the building made from those bricks (e.g.,
wall, house).
Advanced Programming in Python 5
Example
from collections import deque
# Data types
x = 40 # int
name = "Ali" # str
# Data structures (using those types)
numbers = [1, 2, 3, 4] # list (sequence data structure)
student = {"id": 1, "name": "Ali"} # dict (mapping data structure)
queue = deque([1, 2, 3]) # deque (queue data structure)
Advanced Programming in Python 6
Example
from collections import deque
• Data types = define nature of individual
values.
# Data types
x = 40 # int
name = "Ali" # str • Data structures = define how multiple
values (of data types) are organized and
# Data structures (using those types) accessed.
numbers = [1, 2, 3, 4] # list (sequence data structure)
student = {"id": 1, "name": "Ali"} # dict (mapping data structure)
queue = deque([1, 2, 3]) # deque (queue data structure)
Advanced Programming in Python 7
Think!
Are Python’s Basic Data Types also Data Structures?
Advanced Programming in Python 8
Think!
• Basic Data Types: int, float, complex, bool, str, bytes, NoneType.
• They represent atomic values.
• They don’t organize multiple pieces of data (with the partial
exception of str and bytes, which are sequences).
• Python’s basic types are generally not data structures, except for
str and bytes, which behave like sequence data structures.
Advanced Programming in Python 9
In Summary
Data
Layer Category Examples Notes
Structure?
1. Atomic Numbers & single int, float, complex, Single atomic values, not data
No
Types values bool, NoneType structures.
Text & binary str, bytes, Yes Behave like immutable/mutable
sequences bytearray (sequences) sequences of characters/bytes.
2. Built-in Sequence Ordered collections, mutable (list)
list, tuple Yes
Containers containers or immutable (tuple).
Unordered collections of unique
Set containers set, frozenset Yes
elements.
Mapping Key–value pairs, implemented as
dict Yes
containers hash tables.
Advanced Programming in Python 10
In Summary
Data
Layer Category Examples Notes
Structure?
3. Specialized
Containers
Named records namedtuple() Yes Immutable objects with named fields.
(from
collections)
Double-ended queue, efficient
Queues deque Yes
appends/pops from both ends.
Frequency tables Counter Yes Counts occurrences of elements.
Ordered Dict subclass with order-sensitive
OrderedDict Yes
mappings operations.
Default Dict subclass that supplies default values
defaultdict Yes
dictionaries for missing keys.
Context Groups multiple dicts to be searched as
ChainMap Yes
mappings one.
Advanced Programming in Python 11
Built-in Container Types
• Python provides five main built-in container types:
• List
• Tuple
• Set
• Frozenset
• Dict
• Each serves a different purpose and corresponds to an abstract data
type (ADT).
Advanced Programming in Python 13
List
• list → Dynamic Array (Sequence ADT)
• Ordered collection of items.
• Mutable (you can add, remove, or change elements).
• Can store heterogeneous data types.
• Index-based access (zero-based).
Advanced Programming in Python 14
List # Creating lists
nums = [1, 2, 3, 4]
mixed = [1, "hello", 3.5, True]
# Indexing and slicing
print(nums[0]) #1
print(nums[-1]) # 4
print(nums[1:3]) # [2, 3]
# Modifications
nums.append(5) # [1, 2, 3, 4, 5]
nums.insert(2, 99) # [1, 2, 99, 3, 4, 5]
nums.remove(99) # remove by value
popped = nums.pop() # removes last element
# Iteration
for n in nums:
print(n) Advanced Programming in Python 16
Maintains Order, Indexed Access
>>> colors = [
>>> colors[0]
... "red",
'red‘
... "orange",
... "yellow", >>> colors[0] >>> colors[1]
... "green", 'red'
>>> colors[1] 'orange‘
... "blue",
'orange'
... "indigo", >>> colors[2] >>> colors[2]
... "violet" 'yellow'
>>> colors[3] 'yellow‘
... ]
'green'
>>> colors[3]
>>> colors
'green'
['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
Advanced Programming in Python 17
Heterogeneous Data
• This list contains objects of different data types, including an integer
number, string, Boolean value, dictionary, tuple, and another list.
[42, "apple", True, {"name": "John Doe"}, (1, 2, 3), [3.14, 2.78]]
• Even though this feature of lists may seem cool, in practice you’ll find
that lists typically store homogeneous data.
Advanced Programming in Python 18
Constructing a list
>>> cities = [
... "New York", List literals
... "Los Angeles",
• There are several ways to ... "Chicago",
construct a list. ... "Houston",
... "Philadelphia"
• List literals ... ]
• The list() constructor
>>> matrix = [
• A list comprehension ... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]
... ]
>>> inventory = [
... {"product": "phone", "price": 1000, "quantity": 10},
... {"product": "laptop", "price": 1500, "quantity": 5},
... {"product": "tablet", "price": 500, "quantity": 20}
... ]
>>> empty
Advanced = []in Python
Programming 19
Constructing a list
>>> list((0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
• There are several ways to
construct a list. >>> list({"circle", "square", "triangle", "rectangle",
"pentagon"})
• List literals
['square', 'rectangle', 'triangle', 'pentagon', 'circle']
• The list() constructor
• A list comprehension >>> list({"name": "John", "age": 30, "city": "New
York"}.items())
[('name', 'John'), ('age', 30), ('city', 'New York')]
>>> list("Pythonista")
['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 't', 'a']
>>> list()
[]
Advanced Programming in Python 20
Constructing a list
[expression(item) for item in iterable]
• There are several ways to
construct a list.
// construct a list with the square values of the first
• List literals
ten integer numbers
• The list() constructor
• A list comprehension
>>> [number ** 2 for number in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Advanced Programming in Python 21
Constructing a list
[expression(item) for item in iterable]
• There are several ways to
construct a list. >>> [number ** 2 for number in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
• List literals
• The list() constructor Every list comprehension needs at least three
• A list comprehension components:
• In general, you’ll use a list • expression() is a Python expression that returns a
concrete value
comprehension when you
need to create a list of • item is the current object from iterable.
transformed values out of an
existing iterable. • iterable can be any Python iterable object, such
as a list, tuple, set, or string, etc.
Advanced Programming in Python 22
Accessing Items in a List
• lists can contain items of any
type, including other lists and >>> employees = [
sequences. ... (“Ali", 30, "Software Engineer"),
... (“Imran", 25, "Web Developer"),
... (“Alina", 45, "Data Analyst"),
• When you have a list ... (“Maryam", 22, "Intern"),
containing other sequences, ... (“Waqar", 36, "Project Manager")
you can access the items in any ... ]
nested sequence by chaining
// accessing elements
indexing operations. list_of_sequences[index_0][index_1]...[index_n]
Advanced Programming in Python 23
Accessing Items in a List
>>> employees = [
• lists can contain items of any
... (“Ali", 30, "Software Engineer"),
type, including other lists and ... (“Imran", 25, "Web Developer"),
sequences. ... (“Alina", 45, "Data Analyst"),
... (“Maryam", 22, "Intern"),
• When you have a list ... (“Waqar", 36, "Project Manager")
... ]
containing other sequences,
you can access the items in any >>> employees[1][0]
nested sequence by chaining 'Ali'
indexing operations. >>> employees[1][1]
25
>>> employees[1][2]
'Web Developer‘
Advanced Programming in Python 24
List
>>> employees = [
... {"name": “Ali", "age": 30, "job": "Software Engineer"},
... {"name": “Imran", "age": 25, "job": "Web Developer"}, Each record is a
... {"name": “Alina", "age": 45, "job": "Data Analyst"}, key, value pair
... {"name": “Maryam", "age": 22, "job": "Intern"},
... {"name": “Waqar", "age": 36, "job": "Project Manager"}
... ]
>>> employees[3]["name"]
'Maryam' If the nested items are dictionaries, then
>>> employees[3]["age"] you can access their data using keys
22
>>> employees[3]["job"]
Intern
Advanced Programming in Python 25
Retrieving Multiple Items From a List: Slicing
• Another common requirement when working with lists is to extract a
portion, or slice, of a given list.
• You can do this with a slicing operation, which has the following
syntax
list_object[start:stop:step]
• The [start:stop:step] part of this construct is known as the slicing
operator.
• Its syntax consists of a pair of square brackets and three optional
indices, start, stop, and step.
• The second colon is optional. You typically use it only in those cases
where you need a step value different from 1.
Advanced Programming in Python 26
Retrieving Multiple Items From a List: Slicing
• Here’s what the indices in the slicing operator mean:
• start specifies the index at which you want to start the slicing. The
resulting slice includes the item at this index.
• stop specifies the index at which you want the slicing to stop
extracting items. The resulting slice doesn’t include the item at this
index.
• step provides an integer value representing how many items the
slicing will skip on each step. The resulting slice won’t include the
skipped items.
[:]
[: :]
Advanced Programming in Python 27
Retrieving Multiple Items From a List: Slicing
>>> letters = ["A", "a", "B", "b", "C", "c", "D", "d"]
>>> upper_letters = letters[0::2] # Or [::2]
>>> upper_letters
['A', 'B', 'C', 'D']
>>> lower_letters = letters[1::2]
>>> lower_letters
['a', 'b', 'c', 'd']
Advanced Programming in Python 28
Retrieving Multiple Items From a List: Slicing
>>> digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> Gues = digits[:3] >>> Now_What = digits[-3:]
>>> Guess >>> Now_What
[0, 1, 2] [7, 8, 9]
>>> Gues_Again = digits[3:7] >>> And_Now = digits[::2]
>>> Guess_Again >>> And_Now
[3, 4, 5, 6] [0, 2, 4, 6, 8]
>>> Finally = digits[::3]
>>> Finally
[0, 3, 6, 9]
Advanced Programming in Python 29
Retrieving Multiple Items From a List: Slicing
>>> digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> first_three = digits[:3] >>> last_three = digits[-3:]
>>> first_three >>> last_three
[0, 1, 2] [7, 8, 9]
>>> middle_four = digits[3:7] >>> every_other = digits[::2]
>>> middle_four >>> every_other
[3, 4, 5, 6] [0, 2, 4, 6, 8]
>>> every_three = digits[::3]
>>> every_three
[0, 3, 6, 9]
Advanced Programming in Python 30
Slice Object
• Every slicing operation uses a slice object internally.
• The built-in slice() function provides an alternative way to create slice
objects that you can use to extract multiple items from a list.
• returns a slice object equivalent to [start:stop:step]
>>> letters = ["A", "a", "B", "b", "C", "c", "D", "d"]
>>> upper_letters = letters[slice(0, None, 2)]
>>> upper_letters
['A', 'B', 'C', 'D']
>>> lower_letters = letters[slice(1, None, 2)]
>>> lower_letters
['a', 'b', 'c', 'd']
Advanced Programming in Python 31
Creating Copies of a List
• In Python, you’ll have two kinds of mechanisms to create copies of an
existing list. You can create either:
• A shallow copy
• A deep copy
• In Python, you can create aliases of variables using the assignment
operator (=). Assignments don’t create copies of objects in Python.
• Instead, they create bindings between the variable and the object
involved in the assignment.
• Therefore, when you have several aliases of a given list, changes in an
alias will affect the rest of the aliases.
Advanced Programming in Python 32
Aliases
• Note how both variables point to the same object, which you know
because the object’s identity is the same.
>>> countries = [“Pakistan", "Canada", "Poland", "Germany", "Austria"]
>>> nations = countries
>>> id(countries) == id(nations)
True
>>> countries[0] = “Islamic Republic of Pakistan"
>>> nations
[Islamic Republic of Pakistan', 'Canada', 'Poland', 'Germany', 'Austria']
Advanced Programming in Python 33
Shallow Copy
• A shallow copy of an existing list is a new list containing references to
the objects stored in the original list.
• In other words, when you create a shallow copy of a list, Python
constructs a new list with a new identity.
• Then, it inserts references to the objects in the original list into the
new list.
>>> countries = [“Pakistan", "Canada", "Poland", "Germany", "Austria"]
>>> nations = countries[:] //slicing operator
>>> nations
[‘Pakistan', 'Canada', 'Poland', 'Germany', 'Austria']
>>> id(countries) == id(nations)
False
Advanced Programming in Python 34
Shallow Copy
• They’re completely independent list objects.
• However, the elements in nations are aliases of the elements
in countries:
>>> id(nations[0]) == id(countries[0])
True
>>> id(nations[1]) == id(countries[1])
True
Advanced Programming in Python 35
Shallow Copy
• Because making copies of a list is such a common operation, the list
class has a dedicated method for it. The method is called .copy(), and
it returns a shallow copy of the target list
>>> countries = [“Pakistan", "Canada", "Poland", "Germany", "Austria"]
>>> nations = countries.copy()
>>> nations
[‘Pakistan', 'Canada', 'Poland', 'Germany', 'Austria']
>>> id(countries) == id(nations)
False
>>> id(countries[0]) == id(nations[0])
True
>>> id(countries[1]) == id(nations[1])
True
Advanced Programming in Python 36
Deep Copy of a List
• Sometimes you may need to build a complete copy of an existing list.
• In other words, you want a copy that creates a new list object and
also creates new copies of the contained elements.
>>> from copy import deepcopy
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> matrix_copy = deepcopy(matrix)
>>> id(matrix) == id(matrix_copy)
False
>>> id(matrix[0]) == id(matrix_copy[0])
False
>>> id(matrix[1]) == id(matrix_copy[1])
False
Advanced Programming in Python 37
Updating Items in Lists: Index Assignments
• Python lists are mutable data types. This means that you can change
their elements without changing the identity of the underlying list.
• These kinds of changes are commonly known as in-place mutations.
• They allow you to update the value of one or more items in an
existing list.
>>> fruits = ["apple", "banana", "orange", "kiwi", "grape"]
>>> fruits[fruits.index("kiwi")] = "mango"
>>> fruits
['apple', 'banana', 'orange', 'mango', 'grape']
Advanced Programming in Python 38
Updating Items in Lists: Index Assignments
• Access the items with the slicing operator and then use the assignment
operator and an iterable of new values.
• This combination of operators can be called slice assignment for short.
list_object[start:stop:step] = iterable
>>> numbers = [1, 2, 3, 4, 5, 6, 7]
>>> numbers[1:4] = [22, 33, 44]
>>> numbers
[1, 22, 33, 44, 5, 6, 7]
Advanced Programming in Python 39
Updating Items in Lists: Index Assignments
• If iterable has more or fewer elements than the target slice, then
list_object will automatically grow or shrink accordingly.
>>> numbers = [1, 5, 6, 7]
>>> numbers[1:1] = [2, 3, 4]
>>> numbers
[1, 2, 3, 4, 5, 6, 7]
Advanced Programming in Python 40
Updating Items in Lists: Index Assignments
• The initial list has a bunch of zeros where it should have a 3. Your slicing
operator takes the portion filled with zeros and replaces it with a single 3
>>> numbers = [1, 2, 0, 0, 0, 0, 4, 5, 6, 7]
>>> numbers[2:6] = [3]
>>> numbers
[1, 2, 3, 4, 5, 6, 7]
Advanced Programming in Python 41
Appending a Single Item at Once: .append()
• This method allows you to append
items to a list. >>> pets = ["cat", "dog"]
>>> pets.append("parrot")
• The method takes one item at a >>> pets
time and adds it to the right end of ['cat', 'dog', 'parrot']
the target list.
>>> pets.append("gold fish")
>>> pets
['cat', 'dog', 'parrot', 'gold fish']
>>> pets.append("python")
>>> pets
['cat', 'dog', 'parrot', 'gold fish', 'python']
Advanced Programming in Python 42
Appending a Single Item at Once: .append()
• This method allows you to append
items to a list. >>> pets
['cat', 'dog', 'parrot', 'gold fish', 'python']
• The method takes one item at a >> pets.append(“hawk”)
time and adds it to the right end of
the target list. // using slicing operator?
• How to add “hawk” to the list?
Advanced Programming in Python 43
Appending a Single Item at Once: .append()
• This method allows you to append
items to a list. >>> pets
['cat', 'dog', 'parrot', 'gold fish', 'python']
• The method takes one item at a >> pets.append(“hawk”)
time and adds it to the right end of
the target list. // using slicing operator
>>> pets[len(pets):] = ["hawk"]
>>> pets
• How to add “hawk” to the list? ['cat', 'dog', 'parrot', 'gold fish', 'python', 'hawk']
Advanced Programming in Python 44
Appending a Single Item at Once: .append()
• One item at a time!!!
>>> pets.append(["hamster", "turtle"])
>>> pets
[
'cat',
'dog',
'parrot',
'gold fish',
'python',
'hawk',
['hamster', 'turtle']
]
Advanced Programming in Python 45
Extending a List With Multiple Items at Once: .extend()
• The method is called .extend(). It takes an iterable of objects
and appends them as individual items to the end of the target
list
>>> fruits = ["apple", "pear", "peach"]
>>> fruits.extend(["orange", "mango", "banana"])
>>> fruits
['apple', 'pear', 'peach', 'orange', 'mango', 'banana']
Advanced Programming in Python 46
Inserting an Item at a Given Position: .insert()
• The .insert() method is another tool that you can use to add
items to an existing list. This method is a bit different from
.append() and .extend(). >>> letters = ["A", "B", "F", "G"]
>>> letters.insert(2, "C")
>>> letters
['A', 'B', 'C', 'F', 'G']
>>> letters.insert(3, "D")
>>> letters
['A', 'B', 'C', 'D', 'F', 'G']
>>> letters.insert(4, "E")
>>> letters
['A', 'B',Advanced
'C', 'D', 'E', 'F', 'G']
Programming in Python 47
Deleting Items From a List
Delete
Description
Operation
.remove(item) Removes the first occurrence of item from the list. It raises
a ValueError if there’s no such item.
.pop([index]) Removes the item at index and returns it back to the caller. If you
don’t provide a target index, then .pop() removes and returns the
last item in the list. Note that the square brackets
around index mean that the argument is optional. The brackets
aren’t part of the syntax.
.clear() Removes all items from the list.
Advanced Programming in Python 48
.remove() method
>>> sample = [12, 11, 10, 42, 14, 12, 42]
>>> sample.remove(42)
>>> sample
[12, 11, 10, 14, 12, 42]
>>> sample.remove(42)
>>> sample
[12, 11, 10, 14, 12]
>>> sample.remove(42)
Traceback (most recent call last):
...
ValueError: list.remove(x): x not in list
Advanced Programming in Python 49
.pop() method
>>> to_visit = [ >>> visited = to_visit.pop(0)
... "https://realpython.com", >>> visited
... "https://python.org", 'https://realpython.com'
... "https://stackoverflow.com", >>> to_visit
... ] ['https://python.org']
>>> visited = to_visit.pop() >>> visited = to_visit.pop(-1)
>>> visited >>> visited
'https://stackoverflow.com' 'https://python.org'
>>> to_visit >>> to_visit
['https://realpython.com', []
'https://python.org']
Advanced Programming in Python 50
.clear() method
>>> cache = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> cache.clear()
>>> cache
[] >>> cache = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> cache[:] = []
>>> cache
[]
Advanced Programming in Python 51
.clear() method
>>> colors = [
... "red", >>> del colors[-1]
... "orange", >>> colors
... "yellow", ['red', 'yellow', 'green', 'blue', 'indigo']
... "green",
... "blue", >>> del colors[2:4]
... "indigo", >>> colors
... "violet" ['red', 'yellow', 'indigo']
... ]
>>> del colors[:]
>>> del colors[1] >>> colors
>>> colors []
['red', 'yellow', 'green', 'blue', 'indigo', 'violet']
Advanced Programming in Python 52
Traversing a list
>>> for i in range(len(colors)): >>> for i, color in enumerate(colors):
... print(colors[i]) ... print(f"{i} is the index of '{color}'")
... ...
red 0 is the index of 'red'
orange 1 is the index of 'orange'
yellow 2 is the index of 'yellow'
green 3 is the index of 'green'
blue 4 is the index of 'blue'
indigo 5 is the index of 'indigo'
violet 6 is the index of 'violet'
Advanced Programming in Python 53
.reversed() method
>>> for color in reversed(colors):
... print(color)
...
violet
indigo
blue
green
yellow
orange
red
Advanced Programming in Python 54
.sorted() method
>>> numbers = [2, 9, 5, 1, 6]
>>> for number in sorted(numbers):
... print(number)
...
1
2
5
6
9
Advanced Programming in Python 55
.zip() method
>>> integers = [1, 2, 3]
>>> letters = ["a", "b", "c"]
>>> floats = [4.0, 5.0, 6.0]
>>> for i, l, f in zip(integers, letters, floats):
... print(i, l, f)
...
1 a 4.0
2 b 5.0
3 c 6.0
Advanced Programming in Python 56
Some Other Examples
>>> numbers = [2, 9, 5, 1, 6]
• You have a list of numbers, and >>> for number in numbers:
you want to remove only odd ... if number % 2:
values. In this situation, you can ... numbers.remove(number)
try something like this as your ...
>>> numbers
first attempt
[2, 5, 6]
Advanced Programming in Python 57
Some Other Examples
>>> numbers = [2, 9, 5, 1, 6]
• You can iterate over a copy of the >>> for number in numbers[:]:
original list ... if number % 2:
• You use the [:] operator to create ... numbers.remove(number)
a shallow copy of your list. This ...
>>> numbers
copy allows you to iterate over
[2, 6]
the original data in a safe way.
• Once you have the copy, then you
feed it into the for loop, as
before.
Advanced Programming in Python 58
Some Other Examples
>>> numbers = [2, 9, 5, 1, 6]
• When you remove only the last >>> for number in reversed(numbers):
item from the right end of a list ... if number % 2:
on each iteration, you change the ... numbers.remove(number)
list length, but the indexing ...
>>> numbers
remains unaffected.
[2, 6]
• This lets you correctly map
indices to the corresponding list
elements.
Advanced Programming in Python 59
Some Other Examples
>>> numbers_as_strings = ["2", "9", "5",
"1", "6"]
• While modifying list elements
during iteration is less of a >>> numbers_as_integers = []
problem than deleting them, it >>> for number in numbers_as_strings:
also isn’t considered a good ...
numbers_as_integers.append(int(number))
practice.
...
• It’s usually more desirable to
create a completely new list and >>> numbers_as_integers
populate it with the transformed [2, 9, 5, 1, 6]
values
Advanced Programming in Python 60
Building New Lists With Comprehensions
• you have a list of numbers as strings and want to turn them
into integers. You can solve this problem with the following
comprehension
>>> numbers = ["2", "9", "5", "1", "6"]
>>> numbers = [int(number) for number in numbers]
>>> numbers
[2, 9, 5, 1, 6]
Advanced Programming in Python 61
Building New Lists With Comprehensions
>>> numbers = ["2", "9", "5", "1", "6"]
• Both are Equivalent >>> numbers = [int(number) for number in numbers]
>>> numbers
[2, 9, 5, 1, 6]
>>> numbers = ["2", "9", "5", "1", "6"]
>>> for i, number in enumerate(numbers):
... numbers[i] = int(number)
...
>>> numbers
[2, 9, 5, 1, 6]
Advanced Programming in Python 62
Processing Lists with Functional Tools
• The map() function takes a
transformation function and an iterable
as arguments. Then it returns an
iterator that yields items that result >>> numbers = ["2", "9", "5", "1", "6"]
from applying the function to every
>>> numbers = list(map(int, numbers))
item in the iterable >>> numbers
• Using map(), you can convert your list [2, 9, 5, 1, 6]
of numbers to integers
• map() applies int() to every item in
numbers in a loop
Advanced Programming in Python 63
Checking Item Membership
• a membership test is a Boolean test that allows you to find out
whether an object is a member of a collection of values.
>>> usernames = ["john", "jane", "bob", "david", "eve"]
>>> "linda" in usernames
False
>>> "linda" not in usernames
True
>>> "bob" in usernames
True
>>> "bob" not in usernames
False
Advanced Programming in Python 64