Sequence Data Type


Python Sequence Data Type

Sequence means ordered; sequence data type means that data types present in an ordered collection of similar data. Thus, we can store similar data types in an organized way and more efficient fashion in sequence data type.

There are three types of Sequence Data Types in Python:-

  • String
  • List
  • Tuple

STRING

In Python, the string data type can be defined as a sequence of characters represented within quotation marks. The quotations can be single, double, or triple quotes. The plus(+) operator is used to concatenate two strings, and the star operator(*) is known as the repetition operator. The colon operator (:) acts as the slicing operator for a particular string.

Unicode characters are represented by Strings in Python. A string is an array of bytes.
E.g., str0 = “Hello World”
str1 = ‘Hello World’
str2 = “‘Hello World”’
Element of the string can be accessed by string index.

E.g., str0[1] will represent World as output.

List

Lists are similar to arrays. Lists are not necessary to contain the same data type elements, i.e., a list can have different data types for the same variable. It is also quoted inside single or double quote. Python provides you with a syntax through which you can create a nested list.

E.g., List = lis1 = [ [“Hello”, “World”], [HelloWorld”] ]
lis = [“hello”, “1”, “a”, “2”]

We can access the elements of the lists by calling their index.
list1[1]

Returns the second element of the list.

Tuple

Tuples are very similar to list, but lists can be modified, and tuples are immutable. Thus, once you create the tuple, you can not change the elements inside the tuple. Tuple also can have different data type inside its one variable. Tuples are created by putting a comma between the elements and values. Creating a tuple without parentheses is known as Tuple Packing.
Accessing a tuple element is also similar to an array by index. By calling the index, we can call the element of the tuple.

E.g, tup = (a, b, 2, hello)

NOTE: The plus(+) operator is used to concatenate two strings and the star operator(*) is known as the repetition operator. The colon operator (:) acts as the slicing operator for a particular string.

Example :

#Tuple x = ("Knowledge2life", "Knowledge2life 1") print(x) #List x = ["Knowledge2life 1", "Knowledge2life 2", "Knowledge2life 3"] print(x) #string x = "Knowledge2life" print(x)

OUTPUT:

('Knowledge2life', 'Knowledge2life 1')
['Knowledge2life 1', 'Knowledge2life 2', 'Knowledge2life 3']
Knowledge2life