Python literal collections
Python provides four different types of literal collections:
- List literals
- Tuple literals
- Dict literals
- Set literals
List literal
The list contains items of different data types. The values stored in the List are separated by a comma (,) and enclosed within square brackets([]). We can store different types of data in a List. Lists are mutable.
Python3
number = [ 1 , 2 , 3 , 4 , 5 ] name = [ 'Amit' , 'kabir' , 'bhaskar' , 2 ] print (number) print (name) |
Output
[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]
Tuple literal
A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and each element is separated by the comma(,). It is immutable.
Python3
even_number = ( 2 , 4 , 6 , 8 ) odd_number = ( 1 , 3 , 5 , 7 ) print (even_number) print (odd_number) |
Output
(2, 4, 6, 8)
(1, 3, 5, 7)
Dictionary literal
The dictionary stores the data in the key-value pair. It is enclosed by curly braces ‘{}‘ and each pair is separated by the commas(,). We can store different types of data in a dictionary. Dictionaries are mutable.
Python3
alphabets = { 'a' : 'apple' , 'b' : 'ball' , 'c' : 'cat' } information = { 'name' : 'amit' , 'age' : 20 , 'ID' : 20 } print (alphabets) print (information) |
Output
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'name': 'amit', 'age': 20, 'ID': 20}
Set literal
Set is the collection of the unordered data set. It is enclosed by the {} and each element is separated by the comma(,).
Python3
vowels = { 'a' , 'e' , 'i' , 'o' , 'u' } fruits = { "apple" , "banana" , "cherry" } print (vowels) print (fruits) |
Output
{'o', 'e', 'a', 'u', 'i'}
{'apple', 'banana', 'cherry'}
Literals in Python
A literal in Python is a syntax that is used to completely express a fixed value of a specific data type. Literals are constants that are self-explanatory and don’t need to be computed or evaluated. They are used to provide variable values or to directly utilize them in expressions. Generally, literals are a notation for representing a fixed value in source code. They can also be defined as raw values or data given in variables or constants. In this article, we will explore the different types of literals in Python, along with examples to demonstrate their usage.