Search this site
Embedded Files
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
  • More
    • Home
    • Courses
    • Contact

日本語  ❯

Lesson 3    ❮    Lesson List    ❮    Top Page

❯  3.1  Tuples  

3.2 Sets  

3.3 Dictionaries  

3.4 Looping in Dictionaries

3.5 Zip and Enumerate  

⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳  Video   7m 4s
☷  Interactive readings   5m

Making a Tuple

Tuples are used to store multiple items in a single variable. It can be written with round brackets ( ) or simply separating a sequence with commas.

The difference with a list is that the elements of the tuple cannot be changed, added or reordered after the tuple has been created.

Accessing Elements in a Tuple

Getting/slicing element(s) in a tuple is similar as in a list--write after the tuple [index] with the index number inside. You can also use index() and count() just like in list.

The elements inside the tuple cannot be modified as well. 

Using Methods on a Tuple

Due to its unchangeable property, many list methods cannot be applied. However, you can use len(), index() and count() since they are not modifying the tuple.

Making Generator Expression

Generator expression is similar to list comprehension. The resulting object is called a generator.

You cannot print generator directly without converting it to list/tuple first. To convert this into a tuple, you can use tuple(). 

WRITE BETTER CODE
Using Tuples and Lists Smartly

Use a tuple when you know what information goes in the container that it is. For example, when you want to store a person’s information.

But when you want to store similar elements, you should use a list. You can convert a list to a tuple using tuple().

LEARN FROM ERRORS
AttributeError when Applying List Methods to Tuples

As previously mentioned, lists and tuples share the methods index() and count(). However, the methods append(), insert(), remove(), pop(), sort(), and reverse() cannot be used in tuples.

The only fix to these 6 errors is to change the tuple into a list--or delete Line 3-11.

©2023. All rights reserved.  Samy Baladram,
Graduate Program in Data Science - GSIS - Tohoku University
Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse