Collection
means storage location of number of values in same named space location.
There are
four collection data types in the Python programming language:
• List is a collection which is ordered
and changeable. Duplicate elements can be stored in list.
• Tuple is a collection which is
ordered and unchangeable. It also allows duplicate elements.
• Set is a collection which is
unordered and unindexed. Duplicate elements not allowed here.
• Dictionary is a collection which is
unordered and changeable. Duplicate elements not allowed here.
Python
Lists
Lists are
used to store multiple items in a single variable. Lists are created using
square brackets:
Example
Create a
List:
mylist = ["Assam", "Benaras", "Chennai"]
print( mylist)
Output
will be: = [‘Assam’, ‘Benaras’, ‘Chennai’]
List with duplicate values
Example
Lists
allow duplicate values:
mylist = ["Assam", "Benaras", "Chennai", “Assam”]
print( mylist)
Output
will be: = [‘Assam’, ‘Benaras’, ‘Chennai’, ‘Assam’]
List
Length
To
determine how many items a list has, use the len() function:
Example
Print the
number of items in the list:
mylist = ["apple", "banana", "cherry"]
print(len( mylist))
Output
would be: 3
List
Items - Data Types
List
items can be of any data type:
Example
String,
int and boolean data types:
list1 =
["Assam", "Benaras", "Chennai"]
list2 =
[1, 5, 7, 9, 3]
list3 =
[True, False, False]
A list
can contain different data types:
Example
A list
with strings, integers and boolean values:
list1 =
["abc", 34, True, 40, "male"]
type()
From
Python's perspective, lists are defined as objects with the data type 'list':
<class
'list'>
Example
What is
the data type of a list?
mylist =
["apple", "banana", "cherry"]
print(type(mylist))
Output
would be: <class 'list'>
The
list() Constructor
It is
also possible to use the list() constructor when creating a new list.
Example
Using the
list() constructor to make a List:
mylist = list(("Assam", "Benaras", "Chennai")) # note
the double round-brackets