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
|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 =  # 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.
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.
Why does it print “2” ? shouldn’t it print “1” ? Good question.
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!