Day 4: Lists, Tuples, and Sets

Programming

 Day 4: Lists, tuples, and sets

Содержание
  1. Lists
  2. Tuples
  3. Sets

Lists

A list is an ordered, mutable collection of objects. List items are enclosed in square brackets [] and separated by commas.

fruits = ["apple", "banana", &# 34;cherry"] print(fruits) # ["apple", "banana", "cherry"]

You can access list elements by index, starting from zero:

fruits = ["apple", "banana" ;, "cherry"] print(fruits[1]) # "banana"

Tuples

A tuple is similar to a list, but it is immutable, meaning you cannot change, add, or remove elements after the tuple has been created. The elements of the tuple are enclosed in parentheses () and separated by commas.

fruits = ("apple", "banana", "cherry& #34;) print(fruits) # ("apple", "banana", "cherry")

Sets

A set is an unordered collection of unique elements. Set elements are enclosed in curly braces {} and separated by commas.

fruits = {"apple", "banana", "cherry"} print(fruits) # {"apple" , "banana", "cherry"}

Basic operations with lists, tuples, and sets

Adding an element: for lists, use the append() method, for sets, use add(). Tuples cannot add an element after it has been created.

fruits = ["apple", "banana"] fruits.append("cherry") print(fruits) # ["apple", "banana", "cherry"&# 93;

Removing an element: for lists, use the remove() method, which removes the first occurrence of the specified element, for sets, also use remove(). In tuples, you cannot delete an element after it has been created.

fruits = ["apple", "banana", "cherry& #34;] fruits.remove("banana") print(fruits) # ["apple", "cherry"]
You are now familiar with lists, tuples, and sets in Python. In the next lesson, we will look at dictionaries and functions.

Оцените статью
Xrust.com
Добавить комментарий