17 – L2 04 Tuples V3

Python provides another useful container, tuples. Tuples are used to store related pieces of information. A tuple is a data structure in Python that is an immutable ordered sequence of elements. Consider this example involving latitude and longitude. Tuples are similar to lists in that they store an ordered collection of objects which can be accessed by their indices. For example, location zero and location one. Unlike lists however, tuples are immutable. You cannot add or remove items from tuples or sort them in place. Why do we have tuples if they’re like lists with fewer features? Tuples are useful when you have two or more values that are so closely related that they will always be used together, like latitude and longitude coordinates. Tuples can also be used to assign multiple variables in a compact way. Notice that the values assigned to the tuple dimensions aren’t surrounded with parentheses as previous examples were. The parentheses are optional when making tuples and programmers frequently omit them if parentheses don’t clarify the code. In the second line, three variables are assigned from the content of the tuple dimensions, this is called tuple unpacking. You can use tuple unpacking to assign the information from a tuple into multiple variables without having to access them one by one, and make multiple assignment statements. In this example, if we won’t need to use dimensions directly, we could shorten those two lines of code into a single line that assigns three variables in one go.

Dr. Serendipity에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

Continue reading