Lecture 16: Collections in Python: Tuples
Collections in Python: Tuples
A tuple is a collection which is indexed,ordered and immutable elements.
In Python tuples are written with round brackets.
tuple = ("apple", 111, "cherry")
print(tuple)
We can access tuple items by referring to the index number.
print(tuple[1]) # print 111 element from the tuple
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item.
print(tuple[-1]) # print last element from the tuple
print(tuple[-2]) # print second last element from the tuple
We can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
print(tuple[3:5]) # print elements of index 3rd and 4th only
Specify negative indexes if you want to start the search from the end of the tuple.
print(tuple[-4:-1] # print values from -4 to -1 index
tuple = ("apple", 111, "cherry",21)
print(tuple[-1:-4]) # print empty list
print(tuple[:3] # print tuple values from first to index 2
print(tuple[2:] # print tuple values from second index to last
Once a tuple is created, you cannot change its values.
Tuples are unchangeable, or immutable.
If you want to change tuple values, then convert the tuple into a list first, then make changes into the list and convert the list back into a tuple that is the only way.
x = ("Amol", "Suraj", "Kedar")
y = list(x)
y[1] = "Amar"
x = tuple(y)
print(x)
Once a tuple is created, you cannot add items to it as tuples are immutable. tuple[3] = "Samir" # This will raise an error
o create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
tuple = ("Amol",)
print(type(tuple))
tuple1 = ("Samir")
print(type(tuple1)) # not a tuple but it is considered as string type
Remove Items from the tuple:
Tuples are immutable, so we cannot remove items from it, but you can delete the tuple completely.
The del keyword can delete the tuple completely.
del tuple # this will be delete tuple completely
print(tuple) #this will raise an error because the tuple no longer exists
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Lecture 16: Collections in Python: Tuples», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.