Section 2: Python Data Structures

Lecture 2.1: Lists and Tuples

What is a List?

In Python data structure, a list refers to a collection of items that are ordered and malleable, i.e., they can be changed.

Lists are heterogeneous in nature, as they can contain elements of different data types such as integer, string, or even another list.

syntax:

What is a Tuple?

Tuple refers to a structured set of elements that are nevertheless immutable and thus cannot be modified post-creation.

syntax:

FeatureListTuple
FeatureListTuple
MutabilityMutable (can change)Immutable (unchangeable)
Syntax[ ]( )
UsageWhen frequent changes are neededWhen data integrity is crucial

List and Tuple Operations:

Indexing

Both lists and tuples are indexed, starting at 0 for the first element.

Accessing Items:

Slicing:

You can extract specific elements of a list, or a tuple by using slicing.

Syntax: [start:end:step]

Iteration:

Elements can be traversed by iterating over them in the for loops.

  • Example with a list:
  • Example with a Tuple:

Built-in Functions:

Python contributes with quite a few built-in functions that are helpful for both lists and tuples.

len()

Returns the total number of elements in the list or tuple.

Example:

min()

Returns the smallest element in the list or tuple.

Example:

max()

Returns the largest element in the list or tuple.

Example:

2 thoughts on “Section 2: Python Data Structures

  1. Thanks for this great breakdown of lists and tuples in Python! I’ve always found it interesting how they each have their strengths—lists for flexibility and tuples for reliability. The examples really help solidify the concepts too. Quick question—when dealing with larger datasets, do you tend to favor one structure over the other?

    I came across this blog at https://sebbie.pl/tag/python/ that dives into more Python topics. It’s great to see similar content that delves a bit deeper into advanced stuff. Worth checking out for anyone wanting to explore further!

    Thanks again for such an informative post!

Leave a Reply

Your email address will not be published. Required fields are marked *