0% found this document useful (0 votes)
3 views10 pages

Understanding Python Tuples and Lists

Tuples are immutable sequences in Python, defined by comma-separated values in parentheses, and are used for grouping related information and returning multiple values from functions. Lists, on the other hand, are mutable ordered collections that allow item assignment and support various operations such as slicing, concatenation, and membership testing. Both data structures are essential in Python for handling grouped data, with tuples being used for immutable data and lists for mutable data.

Uploaded by

jnaneshprasad16
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views10 pages

Understanding Python Tuples and Lists

Tuples are immutable sequences in Python, defined by comma-separated values in parentheses, and are used for grouping related information and returning multiple values from functions. Lists, on the other hand, are mutable ordered collections that allow item assignment and support various operations such as slicing, concatenation, and membership testing. Both data structures are essential in Python for handling grouped data, with tuples being used for immutable data and lists for mutable data.

Uploaded by

jnaneshprasad16
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What Are Tuples?

• A tuple is a sequence type in Python, similar to a list but immutable, meaning


its contents cannot be changed after creation.
• Tuples are defined by comma-separated values, usually enclosed in
parentheses: e.g., (1,2,3)

Tuple Use Cases

• Used to group related information, such as records or coordinate pairs.


• Common in returning multiple values from a function:
e.g., return (circumference, area

Tuple Assignment: Packing and Unpacking

• Tuple packing: grouping values into a tuple, e.g., student = (B¨ob,¨ 19, C¨S)

• Tuple unpacking: splitting values from a tuple into multiple variables, e.g.,

(name, age, studies) = student

All values on the left are matched to those on the right.

• Number of variables must match number of elements in the tuple, otherwise


you'll get an error.

Tuple Operations

• Slicing and concatenation are possible to create new tuples, e.g., combining or
slicing two tuples.
• Tuples can contain items of different types (heterogeneous), including lists,
other tuples, strings, etc.
• Can be nested and used as keys in dictionaries because they are immutable.

Practical Examples

• Example of a tuple representing a record:

julia = (J¨ulia,¨ R¨oberts,¨ 1967, E¨at Pray Love,¨ 2010, A¨ctress,¨ A¨tlanta, Ge
orgia)¨ Swapping variables using tuple assignment:
(a, b) = (b, a)
Functions and Tuples

Functions can return multiple values as a tuple, making it a convenient way to


send related data together.

Example:

def stats(scores):
return (max(scores), min(scores))

Tuples are fundamental for safely handling grouped, immutable data in Python
and

are a cornerstone of both function returns and heterogenous data grouping in


code

5.3Lists

A list is an ordered collection of elements which can be of any type.

Lists resemble strings (which are sequences of characters), but list elements can
be heterogeneous.

Example of lists:

Python

numbers = [10, 20, 30, 40]


words = ["spam", "bungee", "swallow"]
stuffs = ["hello", 2.0, 5, [10, 20]] # nested list
an_empty_list = []

5.3.2 Accessing Elements

Elements accessed with square brackets [] using zero-based indexing:

python
numbers[0] # 17
numbers[9-8] # 123

Invalid index or non-integer index raises an error.

Common pattern: list traversal using for loop with index or items:

python
for h in horsemen:
print(h)

5.3.3 List Length

len() function returns the number of elements.

Example:

python
len(["car makers", 1, ["Ford", "Toyota", "BMW"], [1, 2, 3]]) # 4

5.3.4 List Membership

• in and not in test membership.

python
"pestilence" in horsemen # TrueExample for counting students enrolled in
"CompSci":
python
counter = 0
for name, subjects in students:
if "CompSci" in subjects:
counter += 1

5.3.5 List Operations

Concatenation (+) and repetition (*) apply to lists:

python
first_list = [1, 2, 3]
second_list = [4, 5, 6]
both_lists = first_list + second_list # [1, 2, 3, 4, 5, 6]
[0] * 4 # [0, 0, 0, 0]

5.3.6 List Slices

Extract sublists using [:] syntax:

python
a_list = ["a", "b", "c", "d", "e", "f"]
a_list[1:3] # ['b', 'c']
a_list[:4] # ['a', 'b', 'c', 'd']
a_list[3:] # ['d', 'e', 'f']
5.3.7 Lists Are Mutable

Lists allow item assignment:

python
fruit = ["banana", "apple", "quince"]
fruit[0] = "pear"
fruit[2] = "orange"

Item assignment does not work on strings (immutable).

Slices can be assigned to replace multiple elements or remove elements:

python
a_list[1:3] = ["x", "y"]
a_list[1:3] = []

5.3.8 List Deletion

del statement to remove element(s):

python
del a[1] # removes second element
del a_list[1:5] # removes multiple elements by slice

5.3.9 Objects and References

Variables refer to [Link] with identical values often refer to the


same object (is operator).

• Lists with identical values do not necessarily refer to the same object:

python
a = [1, 2, 3]
b = [1, 2, 3]
a == b # True
a is b # False

5.3.10 Aliasing

Assignment creates an alias to the same list, not a copy:

python
a = [1, 2, 3]
b=a
b[0] = 5
print(a) # [5, 2, 3]

5.3.11 Cloning Lists

Copy a list by slicing the whole list:

python
a = [1, 2, 3]
b = a[:]
b[0] = 5
print(a) # [1, 2, 3]

5.3.12 Lists and For Loops

Traverse lists directly:

python
friends = ["Joe", "Zoe", "Brad"]
for friend in friends:
print(friend)

Use enumerate to get index and value:

python
for i, val in enumerate(xs):
xs[i] = val ** 2

5.3.13 List Parameters

Lists passed to functions are passed as references (aliases):

python
def double_stuff(stuff_list):
for i, stuff in enumerate(stuff_list):
stuff_list[i] = 2 * stuff

things = [2, 5, 9]
double_stuff(things)
print(things) # [4, 10, 18]

5.3.14 List MethodsCommon methods include:


append(x): add element to end

insert(i, x): insert element at index i

count(x): count occurrences

extend(L): extend list by another list

index(x): find index of first occurrence

remove(x): remove first occurrence

reverse(): reverse list in place

sort(): sort list in place

5.3.15 Pure Functions and Modifiers

Modifiers change lists (side effects).

Pure functions create new lists without modifying inputs:

python
def double_stuff(a_list):
new_list = []
for value in a_list:
new_list.append(2 * value)
return new_list

Using pure functions prevents unintended side effects.

Additional Concepts

Lists can be converted from strings using list(), and range() produces lazy
sequences.

Nested lists (lists inside lists) used for complex data like matrices.

Example of matrix access:

python
mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
mx[1][2] # 6

5.3.13 List Parameters


Passing a list to a function passes a reference (alias) to the original list, not a
copy.

This means changes in the function affect the original list.

Example:

python
def double_stuff(stuff_list):
for index, stuff in enumerate(stuff_list):
stuff_list[index] = 2 * stuff

things = [2, 5, 9]
double_stuff(things)
print(things) # Output: [4, 10, 18]

5.3.14 List Methods

Common list methods include:

append(x): adds an element to the end.

insert(i, x): inserts at position i.

count(x): counts occurrences of x.

extend(list2): appends each element of the second list.

index(x): finds the index of the first occurrence of x.

reverse(): reverses the list in-place.

sort(): sorts the list in ascending order.

remove(x): removes the first occurrence of [Link]:

python
mylist = []
[Link](5)
[Link](1, 12)
print([Link](12)) # 2
[Link]([5, 9, 5, 11])
[Link]()
[Link]()
[Link](12)

5.3.15 Pure Functions and Modifiers

Functions that modify lists in place are called modifiers (with side effects).Pure
functions do not modify inputs; they return new lists instead.

• Example of pure function doubling list elements:

python
def double_stuff(a_list):
new_list = []
for value in a_list:
new_list.append(2 * value)
return new_list

things = [2, 5, 9]
more_things = double_stuff(things)
print(things) # [2, 5, 9]
print(more_things) # [4, 10, 18]

5.3.16 Functions that Produce Lists

A common pattern for functions creating lists:

1. Initialize an empty result list.


2. Loop through items.
3. Create new elements.
4. Append elements to the result.
5. Return the result.

Example: function returning prime numbers less than n:

python
def primes_lessthan(n):
result = []
for i in range(2, n):
if is_prime(i):
[Link](i)
return result

5.3.17 Strings and Lists


String method .split() converts a string into a list of substrings by whitespace or
specified delimiter.

Example:

python
song = "The rain in Spain..."
words = [Link]()
print(words) # ['The', 'rain', 'in', 'Spain...']

parts = [Link]("ai")
print(parts) # ['The r', 'n in Sp', 'n...']

The inverse method .join() concatenates a list of strings into a single string
using a glue string:

python
glue = ";"
phrase = [Link](words)
print(phrase) # 'The;rain;in;Spain...'

5.3.18 List and Range

list() converts iterables to lists.

Example:

python
letters = list("Crunchy Frog")
print(letters) # ['C', 'r', 'u', 'n', 'c', 'h', 'y', ' ', 'F', 'r', 'o', 'g']

range() is lazy and produces numbers on-demand, efficient for large ranges.

Example function finding first integer divisible by 21:

python
def f(n):
for i in range(101, n):
if i % 21 == 0:
return i
print(f(110)) # 105

5.3.19 Looping and Lists


Lists allow repeated computation via loops.

Example comparing summing random numbers by creating a list or summing


on the fly:

python
def sum1():
xs = []
for i in range(10000000):
[Link]([Link](1000))
return sum(xs)

def sum2():
tot = 0
for i in range(10000000):
tot += [Link](1000)
return tot

The second uses less memory and is more efficient.

5.3.20 Nested Lists

Lists can be nested (lists inside lists).

Access elements with chained indexing:

python
nested = ["hello", 2.0, 5, [10, 20]]
print(nested[3]) # [10, 20]
print(nested[3][1]) # 20

5.3.21 Matrices

Nested lists often represent matrices.

A 3x3 matrix example:

python
mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(mx[1]) # [4, 5, 6] (row 1)
print(mx[1][2]) # 6 (element at row 1, col 2)

You might also like