Skip to content
Home » Sequence Conversions in Python

Sequence Conversions in Python

Spread the love

I recently published a couple articles on data type conversions. If you would like to read them, here they are:

String to Number Conversions

Converting String Representations of Binary, Octal and Hexadecimal Integers

Number to String Conversions

String to List Conversions

Today we’ll be talking about sequence conversions. In particular we’ll learn how to convert any sequence to a list or tuple.

Here’s the video version of this article:

Any sequence to list

We can convert any sequence to a list by using the list function:

– string to list:

 >>> s = "hello"
 >>> list(s)                      
 ['h', 'e', 'l', 'l', 'o']

– tuple to list:

>>> tup = (3, "OK", 7.8, "yes")
>>> list(tup)                      
[3, 'OK', 7.8, 'yes']

– range to list:

 >>> rng = range(8)
 >>> list(rng)                      
 [0, 1, 2, 3, 4, 5, 6, 7] 

Any sequence to tuple

We can also convert any sequence to a tuple by using the tuple function:

– string to tuple:

>>> str = "hello"
>>> tuple(str)                      
('h', 'e', 'l', 'l', 'o')

– list to tuple:

 >>> lst = [3, "OK", 7.8, "yes"]
 >>> tuple(lst)                      
 (3, 'OK', 7.8, 'yes')

– range to tuple:

 >>> rng = range(8)
 >>> tuple(rng)                      
 (0, 1, 2, 3, 4, 5, 6, 7) 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply