Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is a sequence in Python

Understanding Sequences in Python

When starting out with programming, especially in Python, you'll come across the term 'sequence' quite often. A sequence, in the most general sense, is a collection of items that are kept in a specific order. Imagine a line of people waiting to buy tickets at a movie theater. Each person has a position in the line: the first, the second, the third, and so on. In Python, a sequence works in a similar way. It's a lineup of items, where each item has its position.

The Basics of Python Sequences

In Python, sequences are not just one type of object but a category of objects. The most common types of sequences you'll encounter are lists, tuples, and strings. Each of these types can hold multiple items in an ordered way. Think of them as different types of trains. A list is like a freight train that can carry any type of cargo. A tuple is like a passenger train that has a fixed set of cars. And a string is like a commuter train that carries a line of people side by side – in this case, characters.

Lists: The Versatile Sequences

Lists in Python are like Swiss Army knives for the collections of items. They are versatile and can hold items of different types. You can add to a list, remove from it, and change items within it.

# Creating a list
my_list = [1, "hello", 3.14]
print(my_list)

This piece of code will output:

[1, 'hello', 3.14]

As you can see, the list my_list contains an integer, a string, and a floating-point number. The items are enclosed in square brackets [], and they are separated by commas.

Tuples: The Immutable Sequences

Tuples are similar to lists, but with one key difference: once you create a tuple, you can't change it. This property is known as immutability. If a list is a notebook with erasable pages, a tuple is a printed book where the text is fixed.

# Creating a tuple
my_tuple = (1, "hello", 3.14)
print(my_tuple)

This will output:

(1, 'hello', 3.14)

Tuples use parentheses () instead of square brackets. Just like lists, they can contain items of different types.

Strings: A Sequence of Characters

Strings in Python are sequences of characters. They are like sentences where each character is a word. You can't change a string once it's created, which makes them immutable like tuples.

# Creating a string
my_string = "Python is fun!"
print(my_string)

This will display:

Python is fun!

Strings are enclosed in either single quotes ' ' or double quotes " ".

Accessing Elements in a Sequence

No matter what type of sequence you're dealing with, you can access its items by their position, known as an index. In Python, indexing starts at 0. So, the first item has an index of 0, the second item has an index of 1, and so on.

# Accessing elements in a list
print(my_list[0])  # Outputs: 1
print(my_list[1])  # Outputs: hello

# Accessing elements in a tuple
print(my_tuple[2])  # Outputs: 3.14

# Accessing elements in a string
print(my_string[10])  # Outputs: u

Modifying Lists

Since lists are mutable, you can change them after they are created. You can add new items, remove items, or change the value of existing items.

# Adding an item to a list
my_list.append("new item")
print(my_list)  # Outputs: [1, 'hello', 3.14, 'new item']

# Changing an item in a list
my_list[1] = "world"
print(my_list)  # Outputs: [1, 'world', 3.14, 'new item']

# Removing an item from a list
del my_list[3]
print(my_list)  # Outputs: [1, 'world', 3.14]

Iterating Over Sequences

One of the most powerful features of sequences is the ability to iterate over them, which means going through each item one by one. In Python, you can use a for loop to do this.

# Iterating over a list
for item in my_list:
    print(item)

# Iterating over a string
for character in my_string:
    print(character)

Sequence Operations

Python provides a variety of operations that you can perform with sequences. For example, you can concatenate (join together) sequences, check if an item is in a sequence, and find the length of a sequence.

# Concatenating sequences
new_list = my_list + ["another item", 2]
print(new_list)  # Outputs: [1, 'world', 3.14, 'another item', 2]

# Checking if an item is in a sequence
print("world" in my_list)  # Outputs: True

# Finding the length of a sequence
print(len(my_string))  # Outputs: 14

Slicing Sequences

Slicing is a way to get a subset of items from a sequence. You specify the start index and the end index, separated by a colon :. Python will return the items from the start index up to, but not including, the end index.

# Slicing a list
print(my_list[0:2])  # Outputs: [1, 'world']

# Slicing a string
print(my_string[7:10])  # Outputs: fun

Conclusion: Embracing the Power of Sequences

As you embark on your journey through the fascinating world of Python, you'll find that sequences are like the beads on a necklace, each one unique and essential to the overall design. They allow you to store and manipulate collections of data with elegance and simplicity. By understanding how to work with lists, tuples, and strings, you'll be able to handle a wide array of programming tasks with confidence.

Remember, learning to program is like learning a new language. It might seem daunting at first, but with practice, you'll start to recognize patterns and become fluent. Sequences are one of the fundamental building blocks of Python, and now that you're familiar with them, you're well on your way to crafting your own programming masterpieces. Keep experimenting with the code examples provided, and don't be afraid to play around and make mistakes. After all, every mistake is a step forward in your coding adventure. Happy coding!