Python - Data Structures Lists Tuples
Python - Data Structures Lists Tuples
Introduction
- So far you have interacted with data types
including int, bool, float and string.
- Today, we are introducing new compound data
types
- Lists
- Tuples
- We will look into methods and functions
associated with these data structures.
- We will look into the idea of aliasing, cloning and
mutability
List
● Ordered sequence of information, accessible by
index.
● a list is denoted by square brackets, []
● a list contains elements
○ usually homogeneous (ie, all integers or all strings)
○ can contain mixed types (not common)
○ list elements can be changed so a list is mutable
● Creating a list:
○ Create an empty list
ages = [] ⇔ empty brackets
ages = list() ⇔ type constructor
○ Creating a list of with elements:
ages = [87, 23, 1, 98] ⇔ using the brackets
ages = 87, 23, 1, 98 ⇔ declare a tuple
list_ages = list(ages) ⇔ use the list constructor
to convert the tuple to a list.
● Unlike arrays, Lists can used to store different types of
data:
x = [1, 2, 3, 4, 5, 6]
a = 7
print(a not in x) # Returns True, if the item is not found in
the list
Aliasing and cloning Lists
● Giving a new name for the existing list
○ This method does not copy the list but rather copies the
reference of the list to the second variable.
x = [20, 30, 40]
y = x # In this case, No separate memory will be allocated for y
○ As you can see, the old value being changed does not affect
the newly copied list.
To find the common items
# To find the common item given two lists
print(common)
Nested List
# To create a list with another list as element
# Method 2
squares = []
squares = [i ** 2 for i in range(1, 6)]
print(squares)
List Comprehensions
lst = []
# Method 1
for i in x:
for j in y:
lst.append(i + j)
# Method 2
lst = [i + j for i in x for j in y]
Repetition operator
mark = (25.000, ) * 4
print(mark) # (25.0, 25.0, 25.0, 25.0)