Introduction to Sequences in Python
In Python, Sequences are the general term for ordered sets. In these Sequences in Python article, we shall talk about each of these sequence types in detail, show how these are used in python programming and provide relevant examples. Sequences are the essential building block of python programming and are used on a daily basis by python developers. There are seven types of sequences in Python.
- Unicode string
- Byte arrays
- Xrange objects
Out of these seven, three are the most popular. These three are: –
For new python developers and learners, this article should create essential learning objectives, for established programmers, this could be a revision module.
Main Concept Of Sequences in Python
Among all sequence types, Lists are the most versatile. A list element can be any object. Lists are mutable which means they can be changed. Its elements can be updated, removed, and also elements can be inserted into it.
Tuples are also like lists, but there is one difference that they are immutable meaning they cannot be changed after defined.
Strings are little different than list and tuples, a string can only store characters. Strings have a special notation.
Following are the operations that can be performed on a sequence: –
- + operator combines two sequences in a process. it is also called concatenation. For example, [1,2,3,4,5] + [6,7] will evaluate to [1,2,3,4,5,6,7].
- * operator repeats a sequence a defined number of times. For example, [1,22]*3 will evaluate to [1,22,1,22,1,22].
- x in NewSeq returns True if x is an element of NewSeq, otherwise False. This statement can be negated with either not (x in NewSeq) or x not in NewSeq.
- NewSeq[i] returns the i’th character of NewSeq. Sequences in Python are indexed from zero, so the first element’s index is 0, the second’s index is 1, and so on.
- NewSeq[-i] returns the i’th element from the end of NewSeq, so NewSeq [-1] will the last element of NewSeq, NewSeq [-2] will be the second -last element.
- All sequences in python can be sliced.
Useful Functions on a sequence: –
- len(NewSeq): This returns the number of elements in the sequence NewSeq. Len stands for length.
Searching on sequences in Python: –
- index(x): will return the index of x’s first occurrence. If there is no x in the NewSeq index, it will throw an error. This error can be handled by an if statement. it can be used to skip this.
- min(NewSeq) and max(NewSeq): will return the smallest and largest elements respectively of NewSeq. For string, this order will be in dictionary order. If any two elements in NewSeq are incomparable for example one a string and another a number, then min and max will throw errors.
- count(x): will return the number of occurrences of x in NewSeq.
A string is represented in single or double quotes: ‘xyz’, “foo-bar”.
Unicode strings are similar to strings but are specified using a preceding “u” character in the syntax: u’abcd’, u”defg”.
4.8 (4,256 ratings)
Lists are represented/created with square brackets with each item separated using commas. Example: -[a, b, c, d].
Tuples are created by the comma operator, but they are not within square brackets. Enclosing parentheses are optional in tuples. However, an empty tuple must use an enclosing parenthesis. Example: – a, b, c or (). A tuple with single item ends with a trailing comma. Ex: – (d,).
Buffer objects too have no built-in Python syntax, and usually, it is created using the built-in function buffer (). Buffers don’t support operations like concatenation or repetition.
Xrange objects are again like buffers. There is no specific syntax for Xrange as well. They can be created using the xrange() function. They too, do not support operations such as slicing, concatenation or repetition. Use of in, not in, min() or max() on Xrange is also inefficient.
Among operations that are supported by most sequence types, “in” and “not in” operations have equal priority as the comparison operations, and “+” and “*” operations have equal priority as the corresponding numeric operations.
Sequences in Python With Examples
In this section, we shall demonstrate examples of sequences in python: –
Slicing and dicing and indexing a string.
>>>"Hello, world!" 'e'
>>>"Hello, world!" 'l'
>>>"Hello, world!" 'l'
>>>"Hello, world!" 'o'
>>"Hello, world!"[3:9] 'lo, wo'
>>>string = "Hello, world!"
>>>string[-9:] 'o, world!'
>>>string[:] 'Hello, world!'
Defining a list and indexing and appending it.
['bacon', 'chicken', 42] >>>spam 'bacon'
['bacon', 'chicken', 42, 10] >>>spam.insert(1, 'and')
['bacon', 'and', 'chicken', 42, 10] >>>spam
['bacon', 'and', 'chicken', 42, 10] >>>del spam >>>spam
['bacon', 'chicken', 42, 10] >>>spam 'bacon'
Various operations on a tuple.
>>>var = "me", "you", "them", “Their”
>>>var = ("me", "you", "them", “Their”)
('me', 'you', 'them', ‘Their’)
Apart from these, there are many other methods and functions are available that can be implemented on strings, lists, and tuple etc. Some such methods for strings are given below: –
• Capitalize ()
• Center(width[, fillchar])
• count(sub[, start[, end]])
• decode([encoding[, errors]])
• encode( [encoding[,errors]])
• endswith( suffix[, start[, end]])
• expandtabs( [tabsize])
• find( sub[, start[, end]])
• index( sub[, start[, end]])
• isalnum( )
• islower( )
• isupper( )
• join( seq)
• replace(old, new[, count])
• startswith( prefix[, start[, end]])
• swapcase( )
Details about these functions will be provided in subsequent articles.
This topic provides a comprehensive understanding of sequences in python. It is expected that students understand the foundations of sequences and must practice given examples on a python IDE or console. From here, students can get ahead with their journey of python programming and if required look for additional practice material on the web or in python practice books. Python language is very much in demand nowadays and having good foundational understanding can benefit students a lot in their future endeavors.
This has been a guide to Sequences in Python. Here we have discussed the Different types of sequences in python and how they are used in python programming with some examples. You may also look at the following article to learn more –