filmov
tv
Python Tuples - Tuple and NamedTuple Type Tutorial with Examples - APPFICIAL
Показать описание
A tuple is like an immutable list, which means that it’s elements cannot be changed. Tuples have similar sequence type functions to lists, such as len. Tuples are created by creating a comma-separated list of values, surrounded by parenthesis. Ex:
disneyland_coordinates = (33.81, 117.92)
friends = (‘Ray’, ‘Alex’, ‘Mirna’)
total_friends = len(friends) # returns 3
Lists are more common than using a tuple. Only use tuples if you want to make sure the values won’t change. For example, the Disneyland coordinates should never change. But in the friends tuple, I may decide not to be friends with Ray anymore and I cannot change or remove him because I put him in a tuple.
Also, element position is important in tuples. In the Disneyland coordinates, we know that the first element is latitude, and second is longitude.
from collections import namedtuple
to the top of your Python program. Here is an example:
Person = namedtuple(‘Person’,[‘name’,’age’,’weight’]) # create a named tuple called Person
bob = Person(‘Bob’, 45, 270.5) # use named tupble to describe a person
mary = Person(‘mary’, 36, 620.9) # use named tupble to describe a person
print(bob)
print(mary)
Subscribe to Appficial for more programming videos coming soon. Also, don't forget to click LIKE and comment on the video if it helped you out!
disneyland_coordinates = (33.81, 117.92)
friends = (‘Ray’, ‘Alex’, ‘Mirna’)
total_friends = len(friends) # returns 3
Lists are more common than using a tuple. Only use tuples if you want to make sure the values won’t change. For example, the Disneyland coordinates should never change. But in the friends tuple, I may decide not to be friends with Ray anymore and I cannot change or remove him because I put him in a tuple.
Also, element position is important in tuples. In the Disneyland coordinates, we know that the first element is latitude, and second is longitude.
from collections import namedtuple
to the top of your Python program. Here is an example:
Person = namedtuple(‘Person’,[‘name’,’age’,’weight’]) # create a named tuple called Person
bob = Person(‘Bob’, 45, 270.5) # use named tupble to describe a person
mary = Person(‘mary’, 36, 620.9) # use named tupble to describe a person
print(bob)
print(mary)
Subscribe to Appficial for more programming videos coming soon. Also, don't forget to click LIKE and comment on the video if it helped you out!
Комментарии