Which of the following can be used to add an item at the end of the list *?

Methods to add elements to List in Python

There are four methods to add elements to a List in Python.

  1. append[]: append the object to the end of the list.
  2. insert[]: inserts the object before the given index.
  3. extend[]: extends the list by appending elements from the iterable.
  4. List Concatenation: We can use + operator to concatenate multiple lists and create a new list.

Append in Python

sunil kumar

Nov 21, 2019·4 min read

Python List insert[]

In this tutorial, we will learn about the Python List insert[] method with the help of examples.

The insert[] method inserts an element to the list at the specified index.

Example

# create a list of vowels vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3 [4th position] vowel.insert[3, 'o']
print['List:', vowel] # Output: List: ['a', 'e', 'i', 'o', 'u']

Add an item to a list in Python [append, extend, insert]

Posted: 2019-05-29 / Modified: 2021-04-06 / Tags: Python, List
Tweet

In Python, use list methods append[], extend[], and insert[] to add items [elements] to a list or combine other lists. You can also use the + operator to combine lists, or use slices to insert items at specific positions.

  • Add an item to the end: append[]
  • Combine lists: extend[], + operator
  • Insert an item at specified index: insert[]
  • Add another list or tuple at specified index: slice
Sponsored Link

Python - Add List Items

❮ Previous Next ❯

Append Items

To add an item to the end of the list, use the append[] method:

Example

Using the append[] method to append an item:

thislist = ["apple", "banana", "cherry"]
thislist.append["orange"]
print[thislist]
Try it Yourself »

Basic conceptsEdit

A regular expression, often called a pattern, specifies a set of strings required for a particular purpose. A simple way to specify a finite set of strings is to list its elements or members. However, there are often more concise ways: for example, the set containing the three strings "Handel", "Händel", and "Haendel" can be specified by the pattern H[ä|ae?]ndel; we say that this pattern matches each of the three strings. However, there can be many ways to write a regular expression for the same set of strings: for example, [Hän|Han|Haen]del also specifies the same set of three strings in this example.

Most formalisms provide the following operations to construct regular expressions.

Boolean "or"A vertical bar separates alternatives. For example, gray|grey can match "gray" or "grey".GroupingParentheses are used to define the scope and precedence of the operators [among other uses]. For example, gray|grey and gr[a|e]y are equivalent patterns which both describe the set of "gray" or "grey".QuantificationA quantifier after a token [such as a character] or group specifies how often that a preceding element is allowed to occur. The most common quantifiers are the question mark ?, the asterisk * [derived from the Kleene star], and the plus sign + [Kleene plus].
?The question mark indicates zero or one occurrences of the preceding element. For example, colou?r matches both "color" and "colour".
*The asterisk indicates zero or more occurrences of the preceding element. For example, ab*c matches "ac", "abc", "abbc", "abbbc", and so on.
+The plus sign indicates one or more occurrences of the preceding element. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".
{n}[19]The preceding item is matched exactly n times.
{min,}[19]The preceding item is matched min or more times.
{,max}[19]The preceding item is matched up to max times.
{min,max}[19]The preceding item is matched at least min times, but not more than max times.
Wildcard

The wildcard . matches any character. For example, a.b matches any string that contains an "a", and then any character and then "b"; and a.*b matches any string that contains an "a", and then the character "b" at some later point.

These constructions can be combined to form arbitrarily complex expressions, much like one can construct arithmetical expressions from numbers and the operations +, −, ×, and ÷. For example, H[ae?|ä]ndel and H[a|ae|ä]ndel are both valid patterns which match the same strings as the earlier example, H[ä|ae?]ndel.

The precise syntax for regular expressions varies among tools and with context; more detail is given in §Syntax.

Formal language theoryEdit

Regular expressions describe regular languages in formal language theory. They have the same expressive power as regular grammars.

Formal definitionEdit

Regular expressions consist of constants, which denote sets of strings, and operator symbols, which denote operations over these sets. The following definition is standard, and found as such in most textbooks on formal language theory.[20][21] Given a finite alphabet Σ, the following constants are defined as regular expressions:

  • [empty set] ∅ denoting the set ∅.
  • [empty string] ε denoting the set containing only the "empty" string, which has no characters at all.
  • [literal character] a in Σ denoting the set containing only the character a.

Given regular expressions R and S, the following operations over them are defined to produce regular expressions:

  • [concatenation] [RS] denotes the set of strings that can be obtained by concatenating a string accepted by R and a string accepted by S [in that order]. For example, let R denote {"ab", "c"} and S denote {"d", "ef"}. Then, [RS] denotes {"abd", "abef", "cd", "cef"}.
  • [alternation] [R|S] denotes the set union of sets described by R and S. For example, if R describes {"ab", "c"} and S describes {"ab", "d", "ef"}, expression [R|S] describes {"ab", "c", "d", "ef"}.
  • [Kleene star] [R*] denotes the smallest superset of the set described by R that contains ε and is closed under string concatenation. This is the set of all strings that can be made by concatenating any finite number [including zero] of strings from the set described by R. For example, if R denotes {"0", "1"}, [R*] denotes the set of all finite binary strings [including the empty string]. If R denotes {"ab", "c"}, [R*] denotes {ε, "ab", "c", "abab", "abc", "cab", "cc", "ababab", "abcab", ... }.

To avoid parentheses it is assumed that the Kleene star has the highest priority, then concatenation and then alternation. If there is no ambiguity then parentheses may be omitted. For example, [ab]c can be written as abc, and a|[b[c*]] can be written as a|bc*. Many textbooks use the symbols ∪, +, or ∨ for alternation instead of the vertical bar.

Examples:

  • a|b* denotes {ε, "a", "b", "bb", "bbb", ...}
  • [a|b]* denotes the set of all strings with no symbols other than "a" and "b", including the empty string: {ε, "a", "b", "aa", "ab", "ba", "bb", "aaa", ...}
  • ab*[c|ε] denotes the set of strings starting with "a", then zero or more "b"s and finally optionally a "c": {"a", "ac", "ab", "abc", "abb", "abbc", ...}
  • [0|[1[01*0]*1]]* denotes the set of binary numbers that are multiples of 3: { ε, "0", "00", "11", "000", "011", "110", "0000", "0011", "0110", "1001", "1100", "1111", "00000", ... }

Expressive power and compactnessEdit

The formal definition of regular expressions is minimal on purpose, and avoids defining ? and +—these can be expressed as follows: a+ = aa*, and a? = [a|ε]. Sometimes the complement operator is added, to give a generalized regular expression; here Rc matches all strings over Σ* that do not match R. In principle, the complement operator is redundant, because it doesn't grant any more expressive power. However, it can make a regular expression much more concise—eliminating a single complement operator can cause a double exponential blow-up of its length.[22][23][24]

Regular expressions in this sense can express the regular languages, exactly the class of languages accepted by deterministic finite automata. There is, however, a significant difference in compactness. Some classes of regular languages can only be described by deterministic finite automata whose size grows exponentially in the size of the shortest equivalent regular expressions. The standard example here is the languages Lk consisting of all strings over the alphabet {a,b} whose kth-from-last letter equalsa. On the one hand, a regular expression describing L4 is given by [a∣b]∗a[a∣b][a∣b][a∣b]{\displaystyle [a\mid b]^{*}a[a\mid b][a\mid b][a\mid b]}.

Generalizing this pattern to Lk gives the expression: [a∣b]∗a[a∣b][a∣b]⋯[a∣b]⏟k−1times.{\displaystyle [a\mid b]^{*}a\underbrace {[a\mid b][a\mid b]\cdots [a\mid b]} _{k-1{\text{ times}}}.\,}

On the other hand, it is known that every deterministic finite automaton accepting the language Lk must have at least 2k states. Luckily, there is a simple mapping from regular expressions to the more general nondeterministic finite automata [NFAs] that does not lead to such a blowup in size; for this reason NFAs are often used as alternative representations of regular languages. NFAs are a simple variation of the type-3 grammars of the Chomsky hierarchy.[20]

In the opposite direction, there are many languages easily described by a DFA that are not easily described by a regular expression. For instance, determining the validity of a given ISBN requires computing the modulus of the integer base 11, and can be easily implemented with an 11-state DFA. However, a regular expression to answer the same problem of divisibility by 11 is at least multiple megabytes in length.[citation needed]

Given a regular expression, Thompson's construction algorithm computes an equivalent nondeterministic finite automaton. A conversion in the opposite direction is achieved by Kleene's algorithm.

Finally, it is worth noting that many real-world "regular expression" engines implement features that cannot be described by the regular expressions in the sense of formal language theory; rather, they implement regexes. See below for more on this.

Deciding equivalence of regular expressionsEdit

As seen in many of the examples above, there is more than one way to construct a regular expression to achieve the same results.

It is possible to write an algorithm that, for two given regular expressions, decides whether the described languages are equal; the algorithm reduces each expression to a minimal deterministic finite state machine, and determines whether they are isomorphic [equivalent].

Algebraic laws for regular expressions can be obtained using a method by Gischer which is best explained along an example: In order to check whether [X+Y]* and [X* Y*]* denote the same regular language, for all regular expressions X, Y, it is necessary and sufficient to check whether the particular regular expressions [a+b]* and [a* b*]* denote the same language over the alphabet Σ={a,b}. More generally, an equation E=F between regular-expression terms with variables holds if, and only if, its instantiation with different variables replaced by different symbol constants holds.[25][26]

Every regular expression can be written solely in terms of the Kleene star and set unions. This is a surprisingly difficult problem. As simple as the regular expressions are, there is no method to systematically rewrite them to some normal form. The lack of axiom in the past led to the star height problem. In 1991, Dexter Kozen axiomatized regular expressions as a Kleene algebra, using equational and Horn clause axioms.[27] Already in 1964, Redko had proved that no finite set of purely equational axioms can characterize the algebra of regular languages.[28]

A regex pattern matches a target string. The pattern is composed of a sequence of atoms. An atom is a single point within the regex pattern which it tries to match to the target string. The simplest atom is a literal, but grouping parts of the pattern to match an atom will require using [] as metacharacters. Metacharacters help form: atoms; quantifiers telling how many atoms [and whether it is a greedy quantifier or not]; a logical OR character, which offers a set of alternatives, and a logical NOT character, which negates an atom's existence; and backreferences to refer to previous atoms of a completing pattern of atoms. A match is made, not when all the atoms of the string are matched, but rather when all the pattern atoms in the regex have matched. The idea is to make a small pattern of characters stand for a large number of possible strings, rather than compiling a large list of all the literal possibilities.

Depending on the regex processor there are about fourteen metacharacters, characters that may or may not have their literal character meaning, depending on context, or whether they are "escaped", i.e. preceded by an escape sequence, in this case, the backslash \. Modern and POSIX extended regexes use metacharacters more often than their literal meaning, so to avoid "backslash-osis" or leaning toothpick syndrome it makes sense to have a metacharacter escape to a literal mode; but starting out, it makes more sense to have the four bracketing metacharacters [] and {} be primarily literal, and "escape" this usual meaning to become metacharacters. Common standards implement both. The usual metacharacters are {}[][]^$.|*+? and \. The usual characters that become metacharacters when escaped are dswDSW and N.

DelimitersEdit

When entering a regex in a programming language, they may be represented as a usual string literal, hence usually quoted; this is common in C, Java, and Python for instance, where the regex re is entered as "re". However, they are often written with slashes as delimiters, as in /re/ for the regex re. This originates in ed, where / is the editor command for searching, and an expression /re/ can be used to specify a range of lines [matching the pattern], which can be combined with other commands on either side, most famously g/re/p as in grep ["global regex print"], which is included in most Unix-based operating systems, such as Linux distributions. A similar convention is used in sed, where search and replace is given by s/re/replacement/ and patterns can be joined with a comma to specify a range of lines as in /re1/,/re2/. This notation is particularly well known due to its use in Perl, where it forms part of the syntax distinct from normal string literals. In some cases, such as sed and Perl, alternative delimiters can be used to avoid collision with contents, and to avoid having to escape occurrences of the delimiter character in the contents. For example, in sed the command s,/,X, will replace a / with an X, using commas as delimiters.

StandardsEdit

The IEEE POSIX standard has three sets of compliance: BRE [Basic Regular Expressions],[29] ERE [Extended Regular Expressions], and SRE [Simple Regular Expressions]. SRE is deprecated,[30] in favor of BRE, as both provide backward compatibility. The subsection below covering the character classes applies to both BRE and ERE.

BRE and ERE work together. ERE adds ?, +, and |, and it removes the need to escape the metacharacters [] and {}, which are required in BRE. Furthermore, as long as the POSIX standard syntax for regexes is adhered to, there can be, and often is, additional syntax to serve specific [yet POSIX compliant] applications. Although POSIX.2 leaves some implementation specifics undefined, BRE and ERE provide a "standard" which has since been adopted as the default syntax of many tools, where the choice of BRE or ERE modes is usually a supported option. For example, GNU grep has the following options: "grep -E" for ERE, and "grep -G" for BRE [the default], and "grep -P" for Perl regexes.

Perl regexes have become a de facto standard, having a rich and powerful set of atomic expressions. Perl has no "basic" or "extended" levels. As in POSIX EREs, [] and {} are treated as metacharacters unless escaped; other metacharacters are known to be literal or symbolic based on context alone. Additional functionality includes lazy matching, backreferences, named capture groups, and recursive patterns.

POSIX basic and extendedEdit

In the POSIX standard, Basic Regular Syntax [BRE] requires that the metacharacters [] and {} be designated \[\] and \{\}, whereas Extended Regular Syntax [ERE] does not.

MetacharacterDescription^.[][^]$[ ]\n*{m,n}
Matches the starting position within the string. In line-based tools, it matches the starting position of any line.
Matches any single character [many applications exclude newlines, and exactly which characters are considered newlines is flavor-, character-encoding-, and platform-specific, but it is safe to assume that the line feed character is included]. Within POSIX bracket expressions, the dot character matches a literal dot. For example, a.c matches "abc", etc., but [a.c] matches only "a", ".", or "c".
A bracket expression. Matches a single character that is contained within the brackets. For example, [abc] matches "a", "b", or "c". [a-z] specifies a range which matches any lowercase letter from "a" to "z". These forms can be mixed: [abcx-z] matches "a", "b", "c", "x", "y", or "z", as does [a-cx-z].

The - character is treated as a literal character if it is the last or the first [after the ^, if present] character within the brackets: [abc-], [-abc]. Note that backslash escapes are not allowed. The ] character can be included in a bracket expression if it is the first [after the ^] character: []abc].

Matches a single character that is not contained within the brackets. For example, [^abc] matches any character other than "a", "b", or "c". [^a-z] matches any single character that is not a lowercase letter from "a" to "z". Likewise, literal characters and ranges can be mixed.
Matches the ending position of the string or the position just before a string-ending newline. In line-based tools, it matches the ending position of any line.
Defines a marked subexpression. The string matched within the parentheses can be recalled later [see the next entry, \n]. A marked subexpression is also called a block or capturing group. BRE mode requires \[\].
Matches what the nth marked subexpression matched, where n is a digit from 1 to 9. This construct is vaguely defined in the POSIX.2 standard. Some tools allow referencing more than nine capturing groups. Also known as a backreference. backreferences are only supported in BRE mode
Matches the preceding element zero or more times. For example, ab*c matches "ac", "abc", "abbbc", etc. [xyz]* matches "", "x", "y", "z", "zx", "zyx", "xyzzy", and so on. [ab]* matches "", "ab", "abab", "ababab", and so on.
Matches the preceding element at least m and not more than n times. For example, a{3,5} matches only "aaa", "aaaa", and "aaaaa". This is not found in a few older instances of regexes. BRE mode requires \{m,n\}.

Examples:

  • .at matches any three-character string ending with "at", including "hat", "cat", "bat", "4at", "#at" and " at" [starting with a space].
  • [hc]at matches "hat" and "cat".
  • [^b]at matches all strings matched by .at except "bat".
  • [^hc]at matches all strings matched by .at other than "hat" and "cat".
  • ^[hc]at matches "hat" and "cat", but only at the beginning of the string or line.
  • [hc]at$ matches "hat" and "cat", but only at the end of the string or line.
  • \[.\] matches any single character surrounded by "[" and "]" since the brackets are escaped, for example: "[a]", "[b]", "[7]", "[@]", "[]]", and "[ ]" [bracket space bracket].
  • s.* matches s followed by zero or more characters, for example: "s", "saw", "seed", "s3w96.7", and "s6#h%[>>>m n mQ".

POSIX extendedEdit

The meaning of metacharacters escaped with a backslash is reversed for some characters in the POSIX Extended Regular Expression [ERE] syntax. With this syntax, a backslash causes the metacharacter to be treated as a literal character. So, for example, \[\] is now [] and \{\} is now {}. Additionally, support is removed for \n backreferences and the following metacharacters are added:

MetacharacterDescription?+|
Matches the preceding element zero or one time. For example, ab?c matches only "ac" or "abc".
Matches the preceding element one or more times. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".
The choice [also known as alternation or set union] operator matches either the expression before or the expression after the operator. For example, abc|def matches "abc" or "def".

Examples:

  • [hc]?at matches "at", "hat", and "cat".
  • [hc]*at matches "at", "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on.
  • [hc]+at matches "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on, but not "at".
  • cat|dog matches "cat" or "dog".

POSIX Extended Regular Expressions can often be used with modern Unix utilities by including the command line flag -E.

Character classesEdit

The character class is the most basic regex concept after a literal match. It makes one small sequence of characters match a larger set of characters. For example, [A-Z] could stand for any uppercase letter in the English alphabet, and \d could mean any digit. Character classes apply to both POSIX levels.

When specifying a range of characters, such as [a-Z] [i.e. lowercase a to uppercase Z], the computer's locale settings determine the contents by the numeric ordering of the character encoding. They could store digits in that sequence, or the ordering could be abc…zABC…Z, or aAbBcC…zZ. So the POSIX standard defines a character class, which will be known by the regex processor installed. Those definitions are in the following table:

DescriptionPOSIXNon-standardPerl/TclVimJavaASCII
ASCII characters[:ascii:][31]\p{ASCII}[\x00-\x7F]
Alphanumeric characters[:alnum:]\p{Alnum}[A-Za-z0-9]
Alphanumeric characters plus "_"[:word:][31]\w\w\w[A-Za-z0-9_]
Non-word characters\W\W\W[^A-Za-z0-9_]
Alphabetic characters[:alpha:]\a\p{Alpha}[A-Za-z]
Space and tab[:blank:]\s\p{Blank}[ \t]
Word boundaries\b\< \>\b[?

Bài mới nhất

Chủ Đề