Python 3 Tutorial for Beginners #06 – Python 3 Sequence Basics

Major python 3 sequence types are str, bytes, bytearray, list, tuple and range. This tutorial focuses on how to create and access sequences.

Python 3 Sequence Types

Type Description
list Mutable sequence of mixed data
tuple Immutable sequence of mixed data
str Immutable sequence of characters
bytes Immutable sequence of integers between 0 <= x < 256
bytearray Mutable sequence of integers between 0 <= x < 256
range Iterable that is calculated dynamically based on given instructions.

We are going to focus on the the first three types for this tutorial.

How to Create Lists, Tuples and Strings

Lists can be created by using [elements,…] syntax.

mylist = [1, 2, 3] # Integer list
mylist = ['hello', 'world'] # String list
mylist = [1, 1.4, 'world'] # Mixed list
mylist = [] # Empty list
mylist = [1] # One element

You can also create tuples.

mytuple = (1, 2, 3) # Integer tuple
mytuple = ('hello', 'world') # String tuple
mytuple = (1, 1.4, 'world') # Mixed tuple
mytuple = () # Empty tuple
mytuple = (1,) # One element tuple (Extra comma is required)

This is how you can define strings.

name = "John Doe"
name = 'John Doe'
name = """John Doe"""
name = '''John Doe"""

How to Repeat a Python 3 Sequence

Python 3 allows you to create a repeated version of a sequence using the “*” operator. Let’s see how we can use this.

Python 3 Sequence Repeat
Python 3 Sequence Repeat

Wow, it works similarly. (Note that this doesn’t work with range)

Accessing a Single Element

You can simply access a single element using var[index] notation. Let’s see how it works.

Access Single Sequence Element
Access Single Sequence Element

Why does it print “2” ? shouldn’t it print “1” ? Good question.

Python 3 Sequence Index Explained
Python 3 Sequence Index Explained

Refer to the above image. All sequence types in python have a zero based index. That is the reason above code snippet print “2” three times.

Looking for more Python? Take a look at our Python tutorials for dabblers. We also have more Python tutorials for beginners. And while you’re here don’t forget to get the scoop on the latest tech news we’ve got just for you!

Like what you see? Subscribe to our email list and hit us with a like on our Facebook page to get the latest news updates and tutorials straight to your newsfeed!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.