Python Tutorial 08
Lists in Python
In Python, a list is a built-in data structure that allows you to store a collection of items. It is an ordered and mutable (changeable) sequence. Each item in a list is called an element and can be of any data type, including numbers, strings, or even other lists. Lists are created using square brackets [ ] and commas , to separate the elements.
Here's an example that demonstrates various operations with lists:
Python Programming Tutorial 08 | List, Tuple, Dictionary |
In the code above, we start by creating a list called fruits with four elements. We can access elements using their index, where the index starts from 0. We can also modify elements by assigning a new value to a specific index.
To add an element to the end of the list, we use the append() method. To remove an element, we use the remove() method and specify the element we want to remove.
The len() function gives us the length of the list, which is the number of elements it contains.
We can iterate over a list using a for loop and perform operations on each element.
Tuples in Python
In Python, a tuple is another built-in data structure that allows you to store a collection of elements, similar to a list. However, unlike lists, tuples are immutable, which means you cannot modify their elements once they are defined. Tuples are created using parentheses () or without any delimiters.
Python Programming Tutorial 08 | List, Tuple, Dictionary |
In the code above, we create a tuple called fruits with three elements. Similar to lists, we can access elements using their index. However, attempting to modify an element in a tuple directly will result in an error because tuples are immutable.
We can use the len() function to determine the length of a tuple, just like with lists.
We can also iterate over a tuple using a for loop and perform operations on each element.
Tuples are commonly used when you have a collection of related values that you don't intend to modify. They can be used to represent coordinates, database records, or any group of values that should remain unchanged.
It's worth noting that although you cannot modify the elements of a tuple directly, you can perform other operations on tuples, such as concatenation, slicing, and tuple unpacking.
Dictionary in Python
Here's an example of how to use a dictionary in Python:
Python Programming Tutorial 08 | List, Tuple, Dictionary |
0 comments:
Post a Comment