learnpython24-(Python List and Tuples)
Python Lists And List Functions
Lists :
Python lists are containers used to store a list of values of any data type. In simple words, we can say that a list is a collection of elements from any data type E.g.
The above list contains strings, an integer, and even an element of type float. A list can contain any kind of data i.e. it’s not mandatory to form a list of only one data type. The list can contain any kind of data in it.
Remember we saw indexing in strings? List elements can also be accessed by using Indices i.e. first element of the list has 0 index and the second element has 1 as its index and so on.
Note: If you put an index which isn’t in the list i.e. that index is not there in list then you will get an error. i.e. if a list named list1 contains 4 elements, list1[4] will throw an error because the list index starts from 0.
Have a look at the examples below:
List Methods :
Here is the list of list methods in Python. These methods can be used in any python list to produce the desired output.
List Slicing :
List slices, like string slices, returns a part of a list extracted out of it. Let me explain, you can use indices to get elements and create list slices as per the following format :
seq = list1[start:stop]
Just like we saw in strings, slicing will go from a start index to stop_index-1. It means the seq list which is a slice of list1 contains elements from the specified start index to specified stop_index – 1.
List Methods:
There are a lot of list methods that make our life easy while using lists in python. Lets have a look at few of them below:
Tuples in Python:
A tuple is an immutable data type in Python. A tuple in python is a collection of elements enclosed in parentheses ()
where items are separated by commas . Tuple once defined can’t be changed i.e. its elements or values can’t be altered or manipulated.
Note: To create a tuple of one element it is necessary to put a comma ‘,’ after that one element like this tup=(1,) because if we have only 1 element inside the parenthesis, the python interpreter will interpret it as a single entity which is why it’s important to use a ‘,’ after the element while creating tuples of a single element.
We can use the slicing operator []
to extract items but we cannot change its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])
# Generates error
# Tuples are immutable
t[0] = 10
Output
t[1] = program t[0:3] = (5, 'program', (1+3j)) Traceback (most recent call last): File "test.py", line 11, in <module> t[0] = 10 TypeError: 'tuple' object does not support item assignment
Swapping of two numbers
Python provides a very handy way of swapping two numbers like below:
Comments
Post a Comment