- Google for Education
- Español – América Latina
- Português – Brasil
- Tiếng Việt
Python Lists
Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0. (See the official python.org list docs .)
Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.
The "empty list" is just an empty pair of brackets [ ]. The '+' works to append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4] (this is just like + with strings).
Python's *for* and *in* constructs are extremely useful, and the first use of them we'll see is with lists. The *for* construct -- for var in list -- is an easy way to look at each element in a list (or other collection). Do not add or remove from the list during iteration.
If you know what sort of thing is in the list, use a variable name in the loop that captures that information such as "num", or "name", or "url". Since Python code does not have other syntax to remind you of types, your variable names are a key way for you to keep straight what is going on. (This is a little misleading. As you gain more exposure to python, you'll see references to type hints which allow you to add typing information to your function definitions. Python doesn't use these type hints when it runs your programs. They are used by other programs such as IDEs (integrated development environments) and static analysis tools like linters/type checkers to validate if your functions are called with compatible arguments.)
The *in* construct on its own is an easy way to test if an element appears in a list (or other collection) -- value in collection -- tests if the value is in the collection, returning True/False.
The for/in constructs are very commonly used in Python code and work on data types other than list, so you should just memorize their syntax. You may have habits from other languages where you start manually iterating over a collection, where in Python you should just use for/in.
You can also use for/in to work on a string. The string acts like a list of its chars, so for ch in s: print(ch) prints all the chars in a string.
The range(n) function yields the numbers 0, 1, ... n-1, and range(a, b) returns a, a+1, ... b-1 -- up to but not including the last number. The combination of the for-loop and the range() function allow you to build a traditional numeric for loop:
There is a variant xrange() which avoids the cost of building the whole list for performance sensitive cases (in Python 3, range() will have the good performance behavior and you can forget about xrange()).
Python also has the standard while-loop, and the *break* and *continue* statements work as in C++ and Java, altering the course of the innermost loop. The above for/in loops solves the common case of iterating over every element in a list, but the while loop gives you total control over the index numbers. Here's a while loop which accesses every 3rd element in a list:
List Methods
Here are some other common list methods.
- list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
- list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.
- list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
- list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError).
- list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present)
- list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is preferred.)
- list.reverse() -- reverses the list in place (does not return it)
- list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).
Notice that these are *methods* on a list object, while len() is a function that takes the list (or string or whatever) as an argument.
Common error: note that the above methods do not *return* the modified list, they just modify the original list.
List Build Up
One common pattern is to start a list as the empty list [], then use append() or extend() to add elements to it:
List Slices
Slices work on lists just as with strings, and can also be used to change sub-parts of the list.
Exercise: list1.py
To practice the material in this section, try the problems in list1.py that do not use sorting (in the Basic Exercises ).
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2024-07-23 UTC.
- Python »
- 3.12.5 Documentation »
- The Python Tutorial »
- 5. Data Structures
- Theme Auto Light Dark |
5. Data Structures ¶
This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.
5.1. More on Lists ¶
The list data type has some more methods. Here are all of the methods of list objects:
Add an item to the end of the list. Equivalent to a[len(a):] = [x] .
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable .
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) .
Remove the first item from the list whose value is equal to x . It raises a ValueError if there is no such item.
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. It raises an IndexError if the list is empty or the index is outside the list range.
Remove all items from the list. Equivalent to del a[:] .
Return zero-based index in the list of the first item whose value is equal to x . Raises a ValueError if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
Return the number of times x appears in the list.
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
Reverse the elements of the list in place.
Return a shallow copy of the list. Equivalent to a[:] .
An example that uses most of the list methods:
You might have noticed that methods like insert , remove or sort that only modify the list have no return value printed – they return the default None . [ 1 ] This is a design principle for all mutable data structures in Python.
Another thing you might notice is that not all data can be sorted or compared. For instance, [None, 'hello', 10] doesn’t sort because integers can’t be compared to strings and None can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, 3+4j < 5+7j isn’t a valid comparison.
5.1.1. Using Lists as Stacks ¶
The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append() . To retrieve an item from the top of the stack, use pop() without an explicit index. For example:
5.1.2. Using Lists as Queues ¶
It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:
5.1.3. List Comprehensions ¶
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
For example, assume we want to create a list of squares, like:
Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:
or, equivalently:
which is more concise and readable.
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:
and it’s equivalent to:
Note how the order of the for and if statements is the same in both these snippets.
If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.
List comprehensions can contain complex expressions and nested functions:
5.1.4. Nested List Comprehensions ¶
The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.
Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:
The following list comprehension will transpose rows and columns:
As we saw in the previous section, the inner list comprehension is evaluated in the context of the for that follows it, so this example is equivalent to:
which, in turn, is the same as:
In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:
See Unpacking Argument Lists for details on the asterisk in this line.
5.2. The del statement ¶
There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:
del can also be used to delete entire variables:
Referencing the name a hereafter is an error (at least until another value is assigned to it). We’ll find other uses for del later.
5.3. Tuples and Sequences ¶
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range ). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple .
A tuple consists of a number of values separated by commas, for instance:
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable , and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples ). Lists are mutable , and their elements are usually homogeneous and are accessed by iterating over the list.
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
The statement t = 12345, 54321, 'hello!' is an example of tuple packing : the values 12345 , 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
5.4. Sets ¶
Python also includes a data type for sets . A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set() , not {} ; the latter creates an empty dictionary, a data structure that we discuss in the next section.
Here is a brief demonstration:
Similarly to list comprehensions , set comprehensions are also supported:
5.5. Dictionaries ¶
Another useful data type built into Python is the dictionary (see Mapping Types — dict ). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys , which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend() .
It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {} . Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del . If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.
Here is a small example using a dictionary:
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
5.6. Looping Techniques ¶
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
Using set() on a sequence eliminates duplicate elements. The use of sorted() in combination with set() over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.
It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.
5.7. More on Conditions ¶
The conditions used in while and if statements can contain any operators, not just comparisons.
The comparison operators in and not in are membership tests that determine whether a value is in (or not in) a container. The operators is and is not compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators.
Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c .
Comparisons may be combined using the Boolean operators and and or , and the outcome of a comparison (or of any other Boolean expression) may be negated with not . These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C . As always, parentheses can be used to express the desired composition.
The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C . When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.
It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,
Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator := . This avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.
5.8. Comparing Sequences and Other Types ¶
Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:
Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.
Table of Contents
- 5.1.1. Using Lists as Stacks
- 5.1.2. Using Lists as Queues
- 5.1.3. List Comprehensions
- 5.1.4. Nested List Comprehensions
- 5.2. The del statement
- 5.3. Tuples and Sequences
- 5.5. Dictionaries
- 5.6. Looping Techniques
- 5.7. More on Conditions
- 5.8. Comparing Sequences and Other Types
Previous topic
4. More Control Flow Tools
- Report a Bug
- Show Source
Lists and Tuples in Python
Table of Contents
Lists Are Ordered
Lists can contain arbitrary objects, list elements can be accessed by index, lists can be nested, lists are mutable, lists are dynamic, defining and using tuples, tuple assignment, packing, and unpacking.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Lists and Tuples in Python
Lists and tuples are arguably Python’s most versatile, useful data types . You will find them in virtually every nontrivial Python program.
Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics of lists and tuples. You’ll learn how to define them and how to manipulate them. When you’re finished, you should have a good feel for when and how to use these object types in a Python program.
Take the Quiz: Test your knowledge with our interactive “Python Lists and Tuples” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Test your understanding of Python lists and tuples.
Python Lists
In short, a list is a collection of arbitrary objects, somewhat akin to an array in many other programming languages but more flexible. Lists are defined in Python by enclosing a comma-separated sequence of objects in square brackets ( [] ), as shown below:
The important characteristics of Python lists are as follows:
- Lists are ordered.
- Lists can contain any arbitrary objects.
- List elements can be accessed by index.
- Lists can be nested to arbitrary depth.
- Lists are mutable.
- Lists are dynamic.
Each of these features is examined in more detail below.
A list is not merely a collection of objects. It is an ordered collection of objects. The order in which you specify the elements when you define a list is an innate characteristic of that list and is maintained for that list’s lifetime. (You will see a Python data type that is not ordered in the next tutorial on dictionaries.)
Lists that have the same elements in a different order are not the same:
A list can contain any assortment of objects. The elements of a list can all be the same type:
Or the elements can be of varying types:
Lists can even contain complex objects, like functions, classes, and modules, which you will learn about in upcoming tutorials:
A list can contain any number of objects, from zero to as many as your computer’s memory will allow:
(A list with a single object is sometimes referred to as a singleton list.)
List objects needn’t be unique. A given object can appear in a list multiple times:
Individual elements in a list can be accessed using an index in square brackets. This is exactly analogous to accessing individual characters in a string. List indexing is zero-based as it is with strings.
Consider the following list:
The indices for the elements in a are shown below:
Here is Python code to access some elements of a :
Virtually everything about string indexing works similarly for lists. For example, a negative list index counts from the end of the list:
Slicing also works. If a is a list, the expression a[m:n] returns the portion of a from index m to, but not including, index n :
Other features of string slicing work analogously for list slicing as well:
Both positive and negative indices can be specified:
Omitting the first index starts the slice at the beginning of the list, and omitting the second index extends the slice to the end of the list:
You can specify a stride—either positive or negative:
The syntax for reversing a list works the same way it does for strings:
The [:] syntax works for lists. However, there is an important difference between how this operation works with a list and how it works with a string.
If s is a string, s[:] returns a reference to the same object:
Conversely, if a is a list, a[:] returns a new object that is a copy of a :
Several Python operators and built-in functions can also be used with lists in ways that are analogous to strings:
The in and not in operators:
The concatenation ( + ) and replication ( * ) operators:
The len() , min() , and max() functions:
It’s not an accident that strings and lists behave so similarly. They are both special cases of a more general object type called an iterable, which you will encounter in more detail in the upcoming tutorial on definite iteration.
By the way, in each example above, the list is always assigned to a variable before an operation is performed on it. But you can operate on a list literal as well:
For that matter, you can do likewise with a string literal:
You have seen that an element in a list can be any sort of object. That includes another list. A list can contain sublists, which in turn can contain sublists themselves, and so on to arbitrary depth.
Consider this (admittedly contrived) example:
The object structure that x references is diagrammed below:
x[0] , x[2] , and x[4] are strings, each one character long:
But x[1] and x[3] are sublists:
To access the items in a sublist, simply append an additional index:
x[1][1] is yet another sublist, so adding one more index accesses its elements:
There is no limit, short of the extent of your computer’s memory, to the depth or complexity with which lists can be nested in this way.
All the usual syntax regarding indices and slicing applies to sublists as well:
However, be aware that operators and functions apply to only the list at the level you specify and are not recursive . Consider what happens when you query the length of x using len() :
x has only five elements—three strings and two sublists. The individual elements in the sublists don’t count toward x ’s length.
You’d encounter a similar situation when using the in operator:
'ddd' is not one of the elements in x or x[1] . It is only directly an element in the sublist x[1][1] . An individual element in a sublist does not count as an element of the parent list(s).
Most of the data types you have encountered so far have been atomic types. Integer or float objects, for example, are primitive units that can’t be further broken down. These types are immutable , meaning that they can’t be changed once they have been assigned. It doesn’t make much sense to think of changing the value of an integer. If you want a different integer, you just assign a different one.
By contrast, the string type is a composite type. Strings are reducible to smaller parts—the component characters. It might make sense to think of changing the characters in a string. But you can’t. In Python, strings are also immutable.
The list is the first mutable data type you have encountered. Once a list has been created, elements can be added, deleted, shifted, and moved around at will. Python provides a wide range of ways to modify lists.
Modifying a Single List Value
A single value in a list can be replaced by indexing and simple assignment:
You may recall from the tutorial Strings and Character Data in Python that you can’t do this with a string:
A list item can be deleted with the del command:
Modifying Multiple List Values
What if you want to change several contiguous elements in a list at one time? Python allows this with slice assignment , which has the following syntax:
Again, for the moment, think of an iterable as a list. This assignment replaces the specified slice of a with <iterable> :
The number of elements inserted need not be equal to the number replaced. Python just grows or shrinks the list as needed.
You can insert multiple elements in place of a single element—just use a slice that denotes only one element:
Note that this is not the same as replacing the single element with a list:
You can also insert elements into a list without removing anything. Simply specify a slice of the form [n:n] (a zero-length slice) at the desired index:
You can delete multiple elements out of the middle of a list by assigning the appropriate slice to an empty list. You can also use the del statement with the same slice:
Prepending or Appending Items to a List
Additional items can be added to the start or end of a list using the + concatenation operator or the += augmented assignment operator :
Note that a list must be concatenated with another list, so if you want to add only one element, you need to specify it as a singleton list:
Note: Technically, it isn’t quite correct to say a list must be concatenated with another list. More precisely, a list must be concatenated with an object that is iterable. Of course, lists are iterable, so it works to concatenate a list with another list.
Strings are iterable also. But watch what happens when you concatenate a string onto a list:
This result is perhaps not quite what you expected. When a string is iterated through, the result is a list of its component characters. In the above example, what gets concatenated onto list a is a list of the characters in the string 'corge' .
If you really want to add just the single string 'corge' to the end of the list, you need to specify it as a singleton list:
If this seems mysterious, don’t fret too much. You’ll learn about the ins and outs of iterables in the tutorial on definite iteration.
Methods That Modify a List
Finally, Python supplies several built-in methods that can be used to modify lists. Information on these methods is detailed below.
Note: The string methods you saw in the previous tutorial did not modify the target string directly. That is because strings are immutable. Instead, string methods return a new string object that is modified as directed by the method. They leave the original target string unchanged:
List methods are different. Because lists are mutable, the list methods shown here modify the target list in place.
a.append(<obj>)
Appends an object to a list.
a.append(<obj>) appends object <obj> to the end of list a :
Remember, list methods modify the target list in place. They do not return a new list:
Remember that when the + operator is used to concatenate to a list, if the target operand is an iterable, then its elements are broken out and appended to the list individually:
The .append() method does not work that way! If an iterable is appended to a list with .append() , it is added as a single object:
Thus, with .append() , you can append a string as a single entity:
a.extend(<iterable>)
Extends a list with the objects from an iterable.
Yes, this is probably what you think it is. .extend() also adds to the end of a list, but the argument is expected to be an iterable. The items in <iterable> are added individually:
In other words, .extend() behaves like the + operator. More precisely, since it modifies the list in place, it behaves like the += operator:
a.insert(<index>, <obj>)
Inserts an object into a list.
a.insert(<index>, <obj>) inserts object <obj> into list a at the specified <index> . Following the method call, a[<index>] is <obj> , and the remaining list elements are pushed to the right:
a.remove(<obj>)
Removes an object from a list.
a.remove(<obj>) removes object <obj> from list a . If <obj> isn’t in a , an exception is raised:
a.pop(index=-1)
Removes an element from a list.
This method differs from .remove() in two ways:
- You specify the index of the item to remove, rather than the object itself.
- The method returns a value: the item that was removed.
a.pop() simply removes the last item in the list:
If the optional <index> parameter is specified, the item at that index is removed and returned. <index> may be negative, as with string and list indexing:
<index> defaults to -1 , so a.pop(-1) is equivalent to a.pop() .
This tutorial began with a list of six defining characteristics of Python lists. The last one is that lists are dynamic. You have seen many examples of this in the sections above. When items are added to a list, it grows as needed:
Similarly, a list shrinks to accommodate the removal of items:
Python Tuples
Python provides another type that is an ordered collection of objects, called a tuple.
Pronunciation varies depending on whom you ask. Some pronounce it as though it were spelled “too-ple” (rhyming with “Mott the Hoople”), and others as though it were spelled “tup-ple” (rhyming with “supple”). My inclination is the latter, since it presumably derives from the same origin as “quintuple,” “sextuple,” “octuple,” and so on, and everyone I know pronounces these latter as though they rhymed with “supple.”
Tuples are identical to lists in all respects, except for the following properties:
- Tuples are defined by enclosing the elements in parentheses ( () ) instead of square brackets ( [] ).
- Tuples are immutable.
Here is a short example showing a tuple definition, indexing, and slicing:
Never fear! Our favorite string and list reversal mechanism works for tuples as well:
Note: Even though tuples are defined using parentheses, you still index and slice tuples using square brackets, just as for strings and lists.
Everything you’ve learned about lists—they are ordered, they can contain arbitrary objects, they can be indexed and sliced, they can be nested—is true of tuples as well. But they can’t be modified:
Why use a tuple instead of a list?
Program execution is faster when manipulating a tuple than it is for the equivalent list. (This is probably not going to be noticeable when the list or tuple is small.)
Sometimes you don’t want data to be modified. If the values in the collection are meant to remain constant for the life of the program, using a tuple instead of a list guards against accidental modification.
There is another Python data type that you will encounter shortly called a dictionary, which requires as one of its components a value that is of an immutable type. A tuple can be used for this purpose, whereas a list can’t be.
In a Python REPL session, you can display the values of several objects simultaneously by entering them directly at the >>> prompt, separated by commas:
Python displays the response in parentheses because it is implicitly interpreting the input as a tuple.
There is one peculiarity regarding tuple definition that you should be aware of. There is no ambiguity when defining an empty tuple, nor one with two or more elements. Python knows you are defining a tuple:
But what happens when you try to define a tuple with one item:
Doh! Since parentheses are also used to define operator precedence in expressions, Python evaluates the expression (2) as simply the integer 2 and creates an int object. To tell Python that you really want to define a singleton tuple, include a trailing comma ( , ) just before the closing parenthesis:
You probably won’t need to define a singleton tuple often, but there has to be a way.
When you display a singleton tuple, Python includes the comma, to remind you that it’s a tuple:
As you have already seen above, a literal tuple containing several items can be assigned to a single object:
When this occurs, it is as though the items in the tuple have been “packed” into the object:
If that “packed” object is subsequently assigned to a new tuple, the individual items are “unpacked” into the objects in the tuple:
When unpacking, the number of variables on the left must match the number of values in the tuple:
Packing and unpacking can be combined into one statement to make a compound assignment:
Again, the number of elements in the tuple on the left of the assignment must equal the number on the right:
In assignments like this and a small handful of other situations, Python allows the parentheses that are usually used for denoting a tuple to be left out:
It works the same whether the parentheses are included or not, so if you have any doubt as to whether they’re needed, go ahead and include them.
Tuple assignment allows for a curious bit of idiomatic Python. Frequently when programming, you have two variables whose values you need to swap. In most programming languages, it is necessary to store one of the values in a temporary variable while the swap occurs like this:
In Python, the swap can be done with a single tuple assignment:
As anyone who has ever had to swap values using a temporary variable knows, being able to do it this way in Python is the pinnacle of modern technological achievement. It will never get better than this.
This tutorial covered the basic properties of Python lists and tuples , and how to manipulate them. You will use these extensively in your Python programming.
One of the chief characteristics of a list is that it is ordered. The order of the elements in a list is an intrinsic property of that list and does not change, unless the list itself is modified. (The same is true of tuples, except of course they can’t be modified.)
The next tutorial will introduce you to the Python dictionary: a composite data type that is unordered. Read on!
🐍 Python Tricks 💌
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
About John Sturtz
John is an avid Pythonista and a member of the Real Python tutorial team.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:
Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!
Keep Learning
Related Topics: basics python
Recommended Video Course: Lists and Tuples in Python
Keep reading Real Python by creating a free account or signing in:
Already have an account? Sign-In
Learn Python practically and Get Certified .
Popular Tutorials
Popular examples, reference materials, learn python interactively, python introduction.
- Get Started With Python
- Your First Python Program
- Python Comments
Python Fundamentals
- Python Variables and Literals
- Python Type Conversion
- Python Basic Input and Output
- Python Operators
Python Flow Control
- Python if...else Statement
- Python for Loop
- Python while Loop
- Python break and continue
- Python pass Statement
Python Data types
- Python Numbers and Mathematics
Python List
Python Tuple
- Python String
- Python Dictionary
- Python Functions
- Python Function Arguments
- Python Variable Scope
- Python Global Keyword
- Python Recursion
- Python Modules
- Python Package
- Python Main function
Python Files
- Python Directory and Files Management
- Python CSV: Read and Write CSV files
- Reading CSV files in Python
- Writing CSV files in Python
- Python Exception Handling
- Python Exceptions
- Python Custom Exceptions
Python Object & Class
- Python Objects and Classes
- Python Inheritance
- Python Multiple Inheritance
- Polymorphism in Python
- Python Operator Overloading
Python Advanced Topics
- List comprehension
- Python Lambda/Anonymous Function
- Python Iterators
- Python Generators
- Python Namespace and Scope
- Python Closures
- Python Decorators
- Python @property decorator
- Python RegEx
Python Date and Time
- Python datetime
- Python strftime()
- Python strptime()
- How to get current date and time in Python?
- Python Get Current Time
- Python timestamp to datetime and vice-versa
- Python time Module
- Python sleep()
Additional Topic
- Precedence and Associativity of Operators in Python
- Python Keywords and Identifiers
- Python Asserts
- Python Json
- Python *args and **kwargs
Python Tutorials
Python List pop()
Python List extend()
Python List insert()
- Python List append()
- Python List index()
- Python List remove()
There are many built-in types in Python that allow us to group and store multiple items. Python lists are the most versatile among them.
For example, we can use a Python list to store a playlist of songs so that we can easily add, remove, and update songs as needed.
- Create a Python List
We create a list by placing elements inside square brackets [] , separated by commas. For example,
Here, the ages list has three items.
We can store data of different data types in a Python list. For example,
We can use the built-in list() function to convert other iterables (strings, dictionaries, tuples, etc.) to a list.
List Characteristics
- Ordered - They maintain the order of elements.
- Mutable - Items can be changed after creation.
- Allow duplicates - They can contain duplicate values.
- Access List Elements
Each element in a list is associated with a number, known as an index .
The index of first item is 0 , the index of second item is 1 , and so on.
We use these index numbers to access list items. For example,
More on Accessing List Elements
Python also supports negative indexing. The index of the last element is -1 , the second-last element is -2 , and so on.
Negative indexing makes it easy to access list items from last.
Let's see an example,
In Python, it is possible to access a section of items from the list using the slicing operator : . For example,
To learn more about slicing, visit Python program to slice lists .
Note : If the specified index does not exist in a list, Python throws the IndexError exception.
- Add Elements to a Python List
We use the append() method to add an element to the end of a Python list. For example,
The insert() method adds an element at the specified index. For example,
We use the extend() method to add elements to a list from other iterables. For example,
- Change List Items
We can change the items of a list by assigning new values using the = operator. For example,
Here, we have replaced the element at index 2: 'Green' with 'Blue' .
- Remove an Item From a List
We can remove an item from a list using the remove() method. For example,
The del statement removes one or more items from a list. For example,
Note : We can also use the del statement to delete the entire list. For example,
- Python List Length
We can use the built-in len() function to find the number of elements in a list. For example,
- Iterating Through a List
We can use a for loop to iterate over the elements of a list. For example,
- Python List Methods
Python has many useful list methods that make it really easy to work with lists.
Method | Description |
---|---|
Adds an item to the end of the list | |
Adds items of lists and other iterables to the end of the list | |
Inserts an item at the specified index | |
Removes the specified value from the list | |
Returns and removes item present at the given index | |
Removes all items from the list | |
Returns the index of the first matched item | |
Returns the count of the specified item in the list | |
Sorts the list in ascending/descending order | |
Reverses the item of the list | |
Returns the shallow copy of the list |
More on Python Lists
List Comprehension is a concise and elegant way to create a list. For example,
To learn more, visit Python List Comprehension .
We use the in keyword to check if an item exists in the list. For example,
- orange is not present in fruits , so, 'orange' in fruits evaluates to False .
- cherry is present in fruits , so, 'cherry' in fruits evaluates to True .
Note: Lists are similar to arrays (or dynamic arrays) in other programming languages. When people refer to arrays in Python, they often mean lists, even though there is a numeric array type in Python.
- Python list()
Table of Contents
- Introduction
Before we wrap up, let’s put your knowledge of Python list to the test! Can you solve the following challenge?
Write a function to find the largest number in a list.
- For input [1, 2, 9, 4, 5] , the return value should be 9 .
Video: Python Lists and Tuples
Sorry about that.
Our premium learning platform, created with over a decade of experience and thousands of feedbacks .
Learn and improve your coding skills like never before.
- Interactive Courses
- Certificates
- 2000+ Challenges
Related Tutorials
Python Library
Python Tutorial
Python Tutorial
File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python assignment operators.
Assignment operators are used to assign values to variables:
Operator | Example | Same As | Try it |
---|---|---|---|
= | x = 5 | x = 5 | |
+= | x += 3 | x = x + 3 | |
-= | x -= 3 | x = x - 3 | |
*= | x *= 3 | x = x * 3 | |
/= | x /= 3 | x = x / 3 | |
%= | x %= 3 | x = x % 3 | |
//= | x //= 3 | x = x // 3 | |
**= | x **= 3 | x = x ** 3 | |
&= | x &= 3 | x = x & 3 | |
|= | x |= 3 | x = x | 3 | |
^= | x ^= 3 | x = x ^ 3 | |
>>= | x >>= 3 | x = x >> 3 | |
<<= | x <<= 3 | x = x << 3 |
Related Pages
COLOR PICKER
Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top Tutorials
Top references, top examples, get certified.
Python List: How To Create, Sort, Append, Remove, And More
The Python list is one of the most used data structures, together with dictionaries . The Python list is not just a list, but can also be used as a stack and even a queue. In this article, I’ll explain everything you might possibly want to know about Python lists:
- how to create lists,
- modify them,
- how to sort lists,
- loop over elements of a list with a for-loop or a list comprehension ,
- how to slice a list,
- append to Python lists,
- … and more!
I’ve included lots of working code examples to demonstrate.
Table of Contents
- 1 How to create a Python list
- 2 Accessing Python list elements
- 3 Adding and removing elements
- 4 How to get List length in Python
- 5 Counting element occurrence in a list
- 6 Check if an item is in a list
- 7 Find the index of an item in a list
- 8 Loop over list elements
- 9 Python list to string
- 10 Sorting Python lists
- 12 Reversing Python lists
- 13 Learn more about Python lists
How to create a Python list
Let’s start by creating a list:
Lists contain regular Python objects, separated by commas and surrounded by brackets. The elements in a list can have any data type , and they can be mixed. You can even create a list of lists. The following lists are all valid:
Using the list() function
Python lists, like all Python data types, are objects. The class of a list is called ‘list’, with a lower case L. If you want to convert another Python object to a list, you can use the list() function, which is actually the constructor of the list class itself. This function takes one argument: an object that is iterable.
So you can convert anything that is iterable into a list. E.g., you can materialize the range function into a list of actual values, or convert a Python set or tuple into a list:
Accessing Python list elements
To access an individual list element, you need to know the position of that element. Since computers start counting at 0, the first element is in position 0, the second element is in position 1, etcetera.
Here are a few examples:
As you can see, you can’t access elements that don’t exist. In this case, Python throws an IndexError exception , with the explanation ‘list index out of range’. In my article on exceptions and the try and except statements , I’ve written about this subject more in-depth in the section on best practices. I recommend you to read it.
Get the last element of a list
If you want to get elements from the end of the list, you can supply a negative value. In this case, we start counting at -1 instead of 0. E.g., to get the last element of a list, you can do this:
Accessing nested list elements
Accessing nested list elements is not that much different. When you access an element that is a list, that list is returned. So to request an element in that list, you need to again use a couple of brackets:
Adding and removing elements
Let’s see how we can add and remove data. There are several ways to remove data from a list. What you use, depends on the situation you’re in. I’ll describe and demonstrate them all in this section.
Append to a Python list
List objects have a number of useful built-in methods, one of which is the append method. When calling append on a list, we append an object to the end of the list:
Combine or merge two lists
Another way of adding elements is adding all the elements from one list to the other. There are two ways to combine lists:
- ‘Add’ them together with the + operator.
- Add all elements of one list to the other with the extend method.
Here’s how you can add two lists together. The result is a new, third list:
The original lists are kept intact. The alternative is to extend one list with another, using the extend method:
While l1 got extended with the elements of l2, l2 stayed the same. Extend appended all values from l2 to l1.
Pop items from a list
The pop() method removes and returns the last item by default unless you give it an index argument.
Here are a couple of examples that demonstrate both the default behavior and the behavior when given an index:
If you’re familiar with the concept of a stack , you can now build one using only the append and pop methods on a list!
Using del() to delete items
There are multiple ways to delete or remove items from a list. While pop returns the item that is deleted from the list, del removes it without returning anything. In fact, you can delete any object, including the entire list, using del:
Remove specific values from a Python list
If you want to remove a specific value instead, you use the remove method. E.g. if you want to remove the first occurrence of the number 2 in a list, you can do so as follows:
As you can see, repeated calls to remove will remove additional twos, until there are none left, in which case Python throws a ValueError exception .
Remove or clear all items from a Python list
To remove all items from a list, use the clear() method:
Remove duplicates from a list
There is no special function or method to remove duplicates from a list, but there are multiple tricks that we can use to do so anyway. The simplest, in my opinion, is using a Python set . Sets are collections of objects, like lists, but can only contain one of each element. More formally, sets are unordered collections of distinct objects.
By converting the list to a set and then back to a list again, we’ve effectively removed all duplicates:
In your own code, you probably want to use this more compact version:
Since sets are very similar to lists, you may not even have to convert them back into a list. If the set offers what you need, use it instead to prevent a double conversion, making your program a little bit faster and more efficient.
Replace items in a list
To replace list items, we assign a new value to a given list index, like so:
How to get List length in Python
In Python, we use the len function to get the length of objects. This is true for lists as well:
If you’re familiar with other programming languages, like Java, you might wonder why Python has a function for this. After all, it could have been one of the built-in methods of a list too, like my_list.len() . This is because, in other languages, this often results in various ways to get an object’s length. E.g., some will call this function len , others will call it length, and yet someone else won’t even implement the function but simply offer a public member variable. And this is exactly the reason why Python chose to standardize the naming of such a common operation!
Counting element occurrence in a list
Don’t confuse the count function with getting the list length, it’s totally different. The built-in count function counts occurrences of a particular value inside that list. Here’s an example:
Since the number 1 occurs three times in the list, my_list.count(1) returned 3.
Check if an item is in a list
To check if an item is in a list, use the following syntax:
Find the index of an item in a list
We can find where an item is inside a list with the index method. For example, in the following list the 4 is located at position 3 (remember that we start counting at zero):
The index method takes two optional parameters: start and stop. With these, we can continue looking for more of the same values. We don’t need to supply an end value if we supply a start value. Now, let’s find both 4’s in the list below:
If you want to do more advanced filtering of lists, you should read my article on list comprehensions .
Loop over list elements
A list is iterable , so we can use a for-loop over the elements of a list just like we can with any other iterable with the ‘for <element> in <iterable>’ syntax:
Python list to string
In Python, you can convert most objects to a string with the str function:
If you’re interested, str is actually the Python string ‘s base class and calling str() constructs a new str object by calling the constructor of the str class. This constructor inspects the provided object and looks for a special method (also called dunder method) called __str__ . If it is present, this method is called. There’s nothing more to it.
If you create your own classes and objects , you can implement the __str__ function yourself to offer a printable version of your objects.
Sorting Python lists
To sort a Python list, we have two options:
- Use the built-in sort method of the list itself.
- Use Python’s built-in sorted() function.
Option one, the built-in method, offers an in-place sort, which means the list itself is modified. In other words, this function does not return anything. Instead, it modifies the list itself.
Option two returns a new list, leaving the original intact. Which one you use depends on the situation you’re in.
In-place list sort in ascending order
Let’s start with the simplest use-case: sorting in ascending order:
In-place list sort in descending order
We can call the sort method with a reverse parameter. If this is set to True, sort reverses the order:
Using sorted()
The following example demonstrates how to sort lists in ascending order, returning a new list with the result:
As you can see from the last statement, the original list is unchanged. Let’s do that again, but now in descending order:
Unsortable lists
We can not sort all lists, since Python can not compare all types with each other. For example, we can sort a list of numbers, like integers and floats, because they have a defined order. We can sort a list of strings as well since Python is able to compare strings too.
However, lists can contain any type of object, and we can’t compare completely different objects, like numbers and strings, to each other. In such cases, Python throws a TypeError :
Although the error might look a bit cryptic, it’s only logical when you know what’s going on. To sort a list, Python needs to compare the objects to each other. So in its sorting algorithm, at some point, it checks if ‘a’ < 1, hence the error: '<' not supported between instances of 'str' and 'int' .
Sometimes you need to get parts of a list. Python has a powerful syntax to do so, called slicing, and it makes working with lists a lot easier compared to some other programming languages. Slicing works on Python lists, but it also works on any other sequence type like strings , tuples , and ranges .
The slicing syntax is as follows:
my_list[start:stop:step]
A couple of notes:
- start is the first element position to include
- stop is exclusive, meaning that the element at position stop won’t be included.
- step is the step size. more on this later.
- start , stop , and step are all optional.
- Negative values can be used too.
To explain how slicing works, it’s best to just look at examples, and try for yourself, so that’s what we’ll do:
The step value
The step value is 1 by default. If you increase it, you can step over elements. Let’s try this:
Going backward
Like with list indexing, we can also supply negative numbers with slicing. Here’s a little ASCII art to show you how counting backward in a list works:
Just remember that you need to set a negative step size in order to go backward:
Reversing Python lists
There are actually three methods you can use to reverse a list in Python:
- An in-place reverse, using the built-in reverse method that every list has natively
- Using list slicing with a negative step size results in a new list
- Create a reverse iterator , with the reversed() function
In the following code crumb, I demonstrate all three. They are explained in detail in the following sections:
Using the built-in reverse method
The list.reverse() method does an in-place reverse, meaning it reorders the list. In other words, the method does not return a new list object, with a reversed order. Here’s how to use reverse() :
Reverse a list with list slicing
Although you can reverse a list with the list.reverse() method that every list has, you can do it with list slicing too, using a negative step size of -1. The difference here is that list slicing results in a new, second list. It keeps the original list intact:
Creating a reverse iterator
Finally, you can use the reversed() built-in function, which creates an iterator that returns all elements of the given iterable (our list) in reverse. This method is quite cheap in terms of CPU and memory usage. All it needs to do is walk backward over the iterable object. It’s doesn’t need to move around data and it doesn’t need to reserve extra memory for a second list. So if you need to iterate over a (large) list in reverse, this should be your choice.
Here’s how you can use this function. Keep in mind, that you can only use the iterator once, but that it’s cheap to make a new one:
Learn more about Python lists
Because there’s a lot to tell about list comprehensions, I created a dedicated article for the topic. A Python list comprehension is a language construct that we use to create a list based on an existing list, without creating for-loops .
Some other resources you might like:
- The official Python docs about lists.
- If you are interested in the internals: lists are often implemented internally as a linked list .
- Python also has arrays , which are very similar and the term will be familiar to people coming from other programming languages. They are more efficient at storing data, but they can only store one type of data.
Get certified with our courses
Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.
Related articles
- Python List Comprehension: Tutorial With Examples
- Python For Loop and While Loop
- Python Tuple: How to Create, Use, and Convert
- Pip Install: How To Install and Remove Python Packages
Python Programming
Practice Python Exercises and Challenges with Solutions
Free Coding Exercises for Python Developers. Exercises cover Python Basics , Data structure , to Data analytics . As of now, this page contains 18 Exercises.
What included in these Python Exercises?
Each exercise contains specific Python topic questions you need to practice and solve. These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges.
- All exercises are tested on Python 3.
- Each exercise has 10-20 Questions.
- The solution is provided for every question.
- Practice each Exercise in Online Code Editor
These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.
Select the exercise you want to solve .
Basic Exercise for Beginners
Practice and Quickly learn Python’s necessary skills by solving simple questions and problems.
Topics : Variables, Operators, Loops, String, Numbers, List
Python Input and Output Exercise
Solve input and output operations in Python. Also, we practice file handling.
Topics : print() and input() , File I/O
Python Loop Exercise
This Python loop exercise aims to help developers to practice branching and Looping techniques in Python.
Topics : If-else statements, loop, and while loop.
Python Functions Exercise
Practice how to create a function, nested functions, and use the function arguments effectively in Python by solving different questions.
Topics : Functions arguments, built-in functions.
Python String Exercise
Solve Python String exercise to learn and practice String operations and manipulations.
Python Data Structure Exercise
Practice widely used Python types such as List, Set, Dictionary, and Tuple operations in Python
Python List Exercise
This Python list exercise aims to help Python developers to learn and practice list operations.
Python Dictionary Exercise
This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations.
Python Set Exercise
This exercise aims to help Python developers to learn and practice set operations.
Python Tuple Exercise
This exercise aims to help Python developers to learn and practice tuple operations.
Python Date and Time Exercise
This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems.
Topics : Date, time, DateTime, Calendar.
Python OOP Exercise
This Python Object-oriented programming (OOP) exercise aims to help Python developers to learn and practice OOP concepts.
Topics : Object, Classes, Inheritance
Python JSON Exercise
Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python
Python NumPy Exercise
Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.
Python Pandas Exercise
Practice Data Analysis using Python Pandas. Practice Data-frame, Data selection, group-by, Series, sorting, searching, and statistics.
Python Matplotlib Exercise
Practice Data visualization using Python Matplotlib. Line plot, Style properties, multi-line plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot.
Random Data Generation Exercise
Practice and Learn the various techniques to generate random data in Python.
Topics : random module, secrets module, UUID module
Python Database Exercise
Practice Python database programming skills by solving the questions step by step.
Use any of the MySQL, PostgreSQL, SQLite to solve the exercise
Exercises for Intermediate developers
The following practice questions are for intermediate Python developers.
If you have not solved the above exercises, please complete them to understand and practice each topic in detail. After that, you can solve the below questions quickly.
Exercise 1: Reverse each word of a string
Expected Output
- Use the split() method to split a string into a list of words.
- Reverse each word from a list
- finally, use the join() function to convert a list into a string
Steps to solve this question :
- Split the given string into a list of words using the split() method
- Use a list comprehension to create a new list by reversing each word from a list.
- Use the join() function to convert the new list into a string
- Display the resultant string
Exercise 2: Read text file into a variable and replace all newlines with space
Given : Assume you have a following text file (sample.txt).
Expected Output :
- First, read a text file.
- Next, use string replace() function to replace all newlines ( \n ) with space ( ' ' ).
Steps to solve this question : -
- First, open the file in a read mode
- Next, read all content from a file using the read() function and assign it to a variable.
- Display final string
Exercise 3: Remove items from a list while iterating
Description :
In this question, You need to remove items from a list while iterating but without creating a different copy of a list.
Remove numbers greater than 50
Expected Output : -
- Get the list's size
- Iterate list using while loop
- Check if the number is greater than 50
- If yes, delete the item using a del keyword
- Reduce the list size
Solution 1: Using while loop
Solution 2: Using for loop and range()
Exercise 4: Reverse Dictionary mapping
Exercise 5: display all duplicate items from a list.
- Use the counter() method of the collection module.
- Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2
Solution 1 : - Using collections.Counter()
Solution 2 : -
Exercise 6: Filter dictionary to contain keys present in the given list
Exercise 7: print the following number pattern.
Refer to Print patterns in Python to solve this question.
- Use two for loops
- The outer loop is reverse for loop from 5 to 0
- Increment value of x by 1 in each iteration of an outer loop
- The inner loop will iterate from 0 to the value of i of the outer loop
- Print value of x in each iteration of an inner loop
- Print newline at the end of each outer loop
Exercise 8: Create an inner function
Question description : -
- Create an outer function that will accept two strings, x and y . ( x= 'Emma' and y = 'Kelly' .
- Create an inner function inside an outer function that will concatenate x and y.
- At last, an outer function will join the word 'developer' to it.
Exercise 9: Modify the element of a nested list inside the following list
Change the element 35 to 3500
Exercise 10: Access the nested key increment from the following dictionary
Under Exercises: -
Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises
Updated on: December 8, 2021 | 52 Comments
Python Date and Time Exercise with Solutions
Updated on: December 8, 2021 | 10 Comments
Python Dictionary Exercise with Solutions
Updated on: May 6, 2023 | 56 Comments
Python Tuple Exercise with Solutions
Updated on: December 8, 2021 | 96 Comments
Python Set Exercise with Solutions
Updated on: October 20, 2022 | 27 Comments
Python if else, for loop, and range() Exercises with Solutions
Updated on: August 29, 2024 | 298 Comments
Updated on: August 2, 2022 | 155 Comments
Updated on: September 6, 2021 | 109 Comments
Python List Exercise with Solutions
Updated on: December 8, 2021 | 201 Comments
Updated on: December 8, 2021 | 7 Comments
Python Data Structure Exercise for Beginners
Updated on: December 8, 2021 | 116 Comments
Python String Exercise with Solutions
Updated on: October 6, 2021 | 221 Comments
Updated on: March 9, 2021 | 23 Comments
Updated on: March 9, 2021 | 51 Comments
Updated on: July 20, 2021 | 29 Comments
Python Basic Exercise for Beginners
Updated on: August 29, 2024 | 498 Comments
Useful Python Tips and Tricks Every Programmer Should Know
Updated on: May 17, 2021 | 23 Comments
Python random Data generation Exercise
Updated on: December 8, 2021 | 13 Comments
Python Database Programming Exercise
Updated on: March 9, 2021 | 17 Comments
- Online Python Code Editor
Updated on: June 1, 2022 |
About PYnative
PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .
Explore Python
- Learn Python
- Python Basics
- Python Databases
- Python Exercises
- Python Quizzes
- Python Tricks
To get New Python Tutorials, Exercises, and Quizzes
Legal Stuff
We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .
Copyright © 2018–2024 pynative.com
How to find first non-blank string variable during string assignment?
I have Python 3.12 on Windows 10.
I work with spreadsheets. I read each row one at a time, and grab one piece of data from that row, let’s say a job number, which could be in column A, B or C. Yes, the spreadsheet is a mess, I can’t change that. I have to work with what I’m given.
But the preferred order I look for the job number in the columns is B, A, C. I need to look for a job in column B. If that’s blank, go to column A. If that’s blank use column C. Currently this requires a bunch of lines to do.
Is there a quicker way to do this?
In perl it was something like (I can’t remember the exact syntax).
In Python I’m currently doing:
This will raise StopIteration if all of cola, colb, colc are empty.
What you did in Perl also works in Python, with slightly different syntax:
This will set job to '' if all of cola, colb, and colc are empty.
Perfect! Thank you! I made a note of this.
Navigation Menu
Search code, repositories, users, issues, pull requests..., provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications You must be signed in to change notification settings
NPTEL Assignment Answers and Solutions 2024 (July-Dec). Get Answers of Week 1 2 3 4 5 6 7 8 8 10 11 12 for all courses. This guide offers clear and accurate answers for your all assignments across various NPTEL courses
progiez/nptel-assignment-answers
Folders and files.
Name | Name | |||
---|---|---|---|---|
164 Commits | ||||
Repository files navigation
Nptel assignment answers 2024 with solutions (july-dec), how to use this repo to see nptel assignment answers and solutions 2024.
If you're here to find answers for specific NPTEL courses, follow these steps:
Access the Course Folder:
- Navigate to the folder of the course you are interested in. Each course has its own folder named accordingly, such as cloud-computing or computer-architecture .
Locate the Weekly Assignment Files:
- Inside the course folder, you will find files named week-01.md , week-02.md , and so on up to week-12.md . These files contain the assignment answers for each respective week.
Select the Week File:
- Click on the file corresponding to the week you are interested in. For example, if you need answers for Week 3, open the week-03.md file.
Review the Answers:
- Each week-XX.md file provides detailed solutions and explanations for that week’s assignments. Review these files to find the information you need.
By following these steps, you can easily locate and use the assignment answers and solutions for the NPTEL courses provided in this repository. We hope this resource assists you in your studies!
List of Courses
Here's a list of courses currently available in this repository:
- Artificial Intelligence Search Methods for Problem Solving
- Cloud Computing
- Computer Architecture
- Cyber Security and Privacy
- Data Science for Engineers
- Data Structure and Algorithms Using Java
- Database Management System
- Deep Learning for Computer Vision
- Deep Learning IIT Ropar
- Digital Circuits
- Ethical Hacking
- Introduction to Industry 4.0 and Industrial IoT
- Introduction to Internet of Things
- Introduction to Machine Learning IIT KGP
- Introduction to Machine Learning
- Introduction to Operating Systems
- ML and Deep Learning Fundamentals and Applications
- Problem Solving Through Programming in C
- Programming DSA Using Python
- Programming in Java
- Programming in Modern C
- Python for Data Science
- Soft Skill Development
- Soft Skills
- Software Engineering
- Software Testing
- The Joy of Computation Using Python
- Theory of Computation
Note: This repository is intended for educational purposes only. Please use the provided answers as a guide to better understand the course material.
📧 Contact Us
For any queries or support, feel free to reach out to us at [email protected] .
🌐 Connect with Progiez
⭐️ Follow Us
Stay updated with our latest content and updates by following us on our social media platforms!
🚀 About Progiez
Progiez is an online educational platform aimed at providing solutions to various online courses offered by NPTEL, Coursera, LinkedIn Learning, and more. Explore our resources for detailed answers and solutions to enhance your learning experience.
Disclaimer: This repository is intended for educational purposes only. All content is provided for reference and should not be submitted as your own work.
Contributors 3
Get notified in your email when a new post is published to this blog
Diving into Function Calling and its JSON Schema in Semantic Kernel Python
Evan Mattson
August 22nd, 2024 0 2
One of the most exciting features available in certain Large Language Models (LLMs) is function-calling. In Semantic Kernel, we handle the heavy lifting so that you can bring your own code or utilize built-in plugins that cater to your use case. Our goal is to make it easy for you to incorporate function calling into your application. Today, we’ll dive into how we create the function-calling JSON schema. This schema is a core piece of functionality that the model requires to decide which function to call for a given context.
For those unfamiliar, function calling refers to executing local code, typically on a user’s machine or as part of their deployment, to satisfy a user’s question or query to an LLM. If you’ve ever asked an LLM to perform any sort of math (without using the code interpreter functionality), you may have noticed it sometimes gives incorrect results. The model predicts the next most probable token in a sequence, so how does it know how to properly add two large numbers like 102982 + 2828381? Unless it has encountered this specific operation frequently during training, it will make its best guess, which may lead to an incorrect answer. So, how do we improve interactions with the model that require a more deterministic approach to finding the correct answer? We use function calling. If you’d like to dive deeper into the underlying concepts of function calling, please visit OpenAI’s function calling documentation .
Semantic Kernel provides various abstractions over different LLMs. When a user configures their execution settings to use function_choice_behavior = FunctionChoiceBehavior.Auto() , this triggers the SDK to include a special JSON payload with the tools attribute in the request settings during a request to the model. In this post, we’ll explore different Semantic Kernel plugin/function configurations and examine how their JSON payloads are constructed and what information is included.
A Simple Example: Adding Two Numbers
Let’s start with a simple example. Suppose I want to add the two numbers mentioned earlier. I can write the following Semantic Kernel (SK) plugin/function:
Although the function and class are simple, let’s walk through it in detail. As the Python script containing this code is interpreted and begins running, the Semantic Kernel SDK looks for functions decorated with the @kernel_function decorator, parses them for their names, input parameters, and output parameters. This information is stored in KernelParameterMetadata which is part of a KernelFunction . The kernel function decorator code examines each input parameter, checking its type, whether it’s annotated, if it has a default value, and more. This is essential because, as we’ll cover shortly, not all kernel functions are defined with primitive type inputs like we’ve done in the simple example. Sometimes we need to dig deeper to understand the types involved, if those types have underlying types, and more. This allows us to accurately determine what the model must send back to the caller during a tool call (in this case, Semantic Kernel, which orchestrates the call to the model) so it can allow for the proper function invocation.
While we’re here, another important aspect is the description provided in the @kernel_function decorator, and the annotations used for the input parameters. This information can help give the model more context about the inputs and how it should respond when it is making a tool call.
JSON Schema for the add_numbers Plugin
As mentioned, the information parsed from a kernel function is stored in KernelParameterMetadata . As we build the JSON schema for the parameter, we determine how the parameter is communicated to the model — is it an integer, a string, a boolean, or an object?
Here’s the JSON schema for the add_numbers plugin:
Just as we expected when defining our kernel function, the two input parameters ( number_one and number_two ) appear as required . When using this kernel plugin/function, the model knows it must return two integers when calling this specific function.
A More Complex Example: Working with Complex Types
Let’s look at a more complex plugin/function definition to see how this works. We’ll start by defining a Pydantic model with two attributes—a start_date and an end_date . The attributes use Pydantic’s Field configuration, allowing us to specify with three dots ( ... ) that the attribute is required, provide a description, and include examples of how the date should be formatted.
Next, we define a new plugin called ComplexTypePlugin . It contains one kernel function named answer_request . As we discussed earlier, the kernel_function decorator’s description provides high-level context to the model. The important input parameter for this kernel function is request of type ComplexRequest . When we parse the function’s input parameters, we store this object type in KernelParameterMetadata so that when building the JSON schema, we can properly recurse into the ComplexRequest class and grab the start_date and end_date attributes. These attributes could even be complex types themselves, but for this example, we don’t need to go that far.
The great thing about using an LLM orchestrator like Semantic Kernel is that we take on the heavy lifting for you. If you interfaced directly with an LLM, you’d have to figure out how to structure the payloads, build the schema, and work with the proper content types.
With this kernel function, we build the following schema for you:
Similar to our add_numbers function, the JSON schema includes our request input parameter, and we dug into its type to identify that we need a start_date string and an end_date string. Both of these attributes are required, as shown in the schema (and by the fact that we didn’t add default values in the method parameters). One of the most useful aspects of function calling is that the model knows which parameters are required for a function and won’t attempt to perform the tool call until it has everything it needs if it decides to use a provided plugin or function based on the conversation’s context.
For example, if I add this plugin/function to a Kernel object, enable function calling, and ask the model:
I can then respond with:
You’ll notice that I didn’t need to format my exact dates in ISO-8601 format. We can tell the model how to format the dates, and it will follow along to the best of its ability. The following dates are what the model returned as part of the function call arguments:
Then, our plugin code that expects the ISO-8601 format can proceed without a hitch.
I wanted to spend some time demystifying what goes on in the Semantic Kernel SDK related to function calling, building the JSON schema, and how to communicate required parameters and their types to the model. To sum up:
- We can provide string descriptions via the kernel_function decorator description parameter and input parameter annotations to help give the model more context about our function or parameters.
- We can define complex objects that use underlying complex type objects, along with annotations or Pydantic models/Fields to give further information and context to the model, which can aid it in choosing the correct function to invoke to complete the user’s query.
For complete implementations around handling auto function calling in Python, please see our code samples here .
As we continue bringing you new features in Semantic Kernel, we want to highlight that we are tracking an issue related adding support for OpenAI’s structured outputs. If you’re looking for a challenge on the Python side and want to help us out with this, please feel free to comment on the open issue we’re tracking or create a GitHub discussion to let us know you’d like to assist with the integration. We’ll be happy to work with you.
Thank you for your time, and we welcome any feedback related to this post or Semantic Kernel in general.
Evan Mattson Senior Software Engineer, Semantic Kernel
Leave a comment Cancel reply
Log in to start the discussion.
Insert/edit link
Enter the destination URL
Or link to existing content
- Python Course
- Python Basics
- Interview Questions
- Python Quiz
- Popular Packages
- Python Projects
- Practice Python
- AI With Python
- Learn Python3
- Python Automation
- Python Web Dev
- DSA with Python
- Python OOPs
- Dictionaries
Assignment Operators in Python
The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python .
Operators |
| ||
---|---|---|---|
| = | Assign the value of the right side of the expression to the left side operand | c = a + b |
| += | Add right side operand with left side operand and then assign the result to left operand | a += b |
| -= | Subtract right side operand from left side operand and then assign the result to left operand | a -= b |
| *= | Multiply right operand with left operand and then assign the result to the left operand | a *= b |
| /= | Divide left operand with right operand and then assign the result to the left operand | a /= b |
| %= | Divides the left operand with the right operand and then assign the remainder to the left operand | a %= b |
| //= | Divide left operand with right operand and then assign the value(floor) to left operand | a //= b |
| **= | Calculate exponent(raise power) value using operands and then assign the result to left operand | a **= b |
| &= | Performs Bitwise AND on operands and assign the result to left operand | a &= b |
| |= | Performs Bitwise OR on operands and assign the value to left operand | a |= b |
| ^= | Performs Bitwise XOR on operands and assign the value to left operand | a ^= b |
| >>= | Performs Bitwise right shift on operands and assign the result to left operand | a >>= b |
| <<= | Performs Bitwise left shift on operands and assign the result to left operand | a <<= b |
| := | Assign a value to a variable within an expression | a := exp |
Here are the Assignment Operators in Python with examples.
Assignment Operator
Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand.
Addition Assignment Operator
The Addition Assignment Operator is used to add the right-hand side operand with the left-hand side operand and then assigning the result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the addition assignment operator which will first perform the addition operation and then assign the result to the variable on the left-hand side.
S ubtraction Assignment Operator
The Subtraction Assignment Operator is used to subtract the right-hand side operand from the left-hand side operand and then assigning the result to the left-hand side operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the subtraction assignment operator which will first perform the subtraction operation and then assign the result to the variable on the left-hand side.
M ultiplication Assignment Operator
The Multiplication Assignment Operator is used to multiply the right-hand side operand with the left-hand side operand and then assigning the result to the left-hand side operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the multiplication assignment operator which will first perform the multiplication operation and then assign the result to the variable on the left-hand side.
D ivision Assignment Operator
The Division Assignment Operator is used to divide the left-hand side operand with the right-hand side operand and then assigning the result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the division assignment operator which will first perform the division operation and then assign the result to the variable on the left-hand side.
M odulus Assignment Operator
The Modulus Assignment Operator is used to take the modulus, that is, it first divides the operands and then takes the remainder and assigns it to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the modulus assignment operator which will first perform the modulus operation and then assign the result to the variable on the left-hand side.
F loor Division Assignment Operator
The Floor Division Assignment Operator is used to divide the left operand with the right operand and then assigs the result(floor value) to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the floor division assignment operator which will first perform the floor division operation and then assign the result to the variable on the left-hand side.
Exponentiation Assignment Operator
The Exponentiation Assignment Operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the exponentiation assignment operator which will first perform exponent operation and then assign the result to the variable on the left-hand side.
Bitwise AND Assignment Operator
The Bitwise AND Assignment Operator is used to perform Bitwise AND operation on both operands and then assigning the result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise AND assignment operator which will first perform Bitwise AND operation and then assign the result to the variable on the left-hand side.
Bitwise OR Assignment Operator
The Bitwise OR Assignment Operator is used to perform Bitwise OR operation on the operands and then assigning result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise OR assignment operator which will first perform bitwise OR operation and then assign the result to the variable on the left-hand side.
Bitwise XOR Assignment Operator
The Bitwise XOR Assignment Operator is used to perform Bitwise XOR operation on the operands and then assigning result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise XOR assignment operator which will first perform bitwise XOR operation and then assign the result to the variable on the left-hand side.
Bitwise Right Shift Assignment Operator
The Bitwise Right Shift Assignment Operator is used to perform Bitwise Right Shift Operation on the operands and then assign result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise right shift assignment operator which will first perform bitwise right shift operation and then assign the result to the variable on the left-hand side.
Bitwise Left Shift Assignment Operator
The Bitwise Left Shift Assignment Operator is used to perform Bitwise Left Shift Opertator on the operands and then assign result to the left operand.
Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise left shift assignment operator which will first perform bitwise left shift operation and then assign the result to the variable on the left-hand side.
Walrus Operator
The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression.
Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop . The operator will solve the expression on the right-hand side and assign the value to the left-hand side operand ‘x’ and then execute the remaining code.
Assignment Operators in Python – FAQs
What are assignment operators in python.
Assignment operators in Python are used to assign values to variables. These operators can also perform additional operations during the assignment. The basic assignment operator is = , which simply assigns the value of the right-hand operand to the left-hand operand. Other common assignment operators include += , -= , *= , /= , %= , and more, which perform an operation on the variable and then assign the result back to the variable.
What is the := Operator in Python?
The := operator, introduced in Python 3.8, is known as the “walrus operator”. It is an assignment expression, which means that it assigns values to variables as part of a larger expression. Its main benefit is that it allows you to assign values to variables within expressions, including within conditions of loops and if statements, thereby reducing the need for additional lines of code. Here’s an example: # Example of using the walrus operator in a while loop while (n := int(input("Enter a number (0 to stop): "))) != 0: print(f"You entered: {n}") This loop continues to prompt the user for input and immediately uses that input in both the condition check and the loop body.
What is the Assignment Operator in Structure?
In programming languages that use structures (like C or C++), the assignment operator = is used to copy values from one structure variable to another. Each member of the structure is copied from the source structure to the destination structure. Python, however, does not have a built-in concept of ‘structures’ as in C or C++; instead, similar functionality is achieved through classes or dictionaries.
What is the Assignment Operator in Python Dictionary?
In Python dictionaries, the assignment operator = is used to assign a new key-value pair to the dictionary or update the value of an existing key. Here’s how you might use it: my_dict = {} # Create an empty dictionary my_dict['key1'] = 'value1' # Assign a new key-value pair my_dict['key1'] = 'updated value' # Update the value of an existing key print(my_dict) # Output: {'key1': 'updated value'}
What is += and -= in Python?
The += and -= operators in Python are compound assignment operators. += adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand. Conversely, -= subtracts the right-hand operand from the left-hand operand and assigns the result to the left-hand operand. Here are examples of both: # Example of using += a = 5 a += 3 # Equivalent to a = a + 3 print(a) # Output: 8 # Example of using -= b = 10 b -= 4 # Equivalent to b = b - 4 print(b) # Output: 6 These operators make code more concise and are commonly used in loops and iterative data processing.
Please Login to comment...
Similar reads.
- Python-Operators
- How to Get a Free SSL Certificate
- Best SSL Certificates Provider in India
- Elon Musk's xAI releases Grok-2 AI assistant
- What is OpenAI SearchGPT? How it works and How to Get it?
- Content Improvement League 2024: From Good To A Great Article
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
Python list of lists assignment
One thing first: No, this is not a question about why
gives [1,1,1,1,1,1,1,1,1,1].
My question is a bit more tricky: I do the folling:
Now I assign a value:
And now another one:
It gives me an IndexError: list assignment index out of range.
How can I make this work? As you can see, I want an empty list that contains 3 other lists to which i can append values.
Thanks in advance!
- 1 Did you look at what x[0] = 1 actually does? It replaces one of your nested lists with the number 1. If you want to append values, you should use append , not item assignment. – BrenBarn Commented Apr 29, 2014 at 8:19
- yes you are right. but this is only an example. in my implementation, i do use append ;) – PKlumpp Commented Apr 29, 2014 at 8:31
4 Answers 4
I want an empty list that contains 3 other lists to which i can append values.
Your problem correctly stated is: "I want a list of three empty lists" (something cannot be empty and contain things at the same time).
If you want that, why are you doing it in such a convoluted way? What's wrong with the straightforward approach:
If you have such a list, when you do empty_list[0] = 1 , what you end up with is:
Instead, you should do empty_list[0].append(1) , which will give you:
If you want to create an arbitrary number of nested lists:
- good question! the answer is simple: my 3 lists in one list were only an example. originally, i wanted to put 15 lists into a list. of course, your way is working, but it looks somewhat weird if i implement it that way. i just wanted to learn if there is an advanced way of doing this. but thanks ;) – PKlumpp Commented Apr 29, 2014 at 8:29
gives [1,1,1,1,1,1,1,1,1,1] ? It's an index error (you can't assign at a nonexisting index), because actually []*10 == [] . Your code does exactly the same (I mean an index error). This line
is short (or not) for
so x[1] is an index error.
- sry, you are right, i forgot brackets there. Yes i know the index does not exist, that is what the error message already told me. but how do i solve my problem? – PKlumpp Commented Apr 29, 2014 at 8:27
- @ZerO I want an empty list that contains 3 other lists I don't understand - it can be empty and contain something at the same time. If you want to append something to a list, then use .append . See Burhan's answer. – freakish Commented Apr 29, 2014 at 9:04
Maybe something like this could work.
The output would be:
If you would like to access/add elements, you could:
- yes, this does work. but i need a multi-assignment ;) – PKlumpp Commented Apr 29, 2014 at 11:35
Comparing the output of:
may help answer your finding.
- are you kidding me? Did you even read my question? I think i clearly showed that this is NOT the problem -.- – PKlumpp Commented Apr 30, 2014 at 6:56
- @ZerO: Did you even try the above code? I see no bearing on your question apart from the subtle but significant difference shown by the above. You have a 10 in your first example, and a 3 in your second. Why? If you already knew the difference between multiplication of lists versus generators, then print i and print i[0] and print i[1] as well and see why you are getting an IndexError . I am on SO thinking I like to learn and help, and I may be wrong in my answer. – vapace Commented Apr 30, 2014 at 16:32
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Sign up or log in
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Not the answer you're looking for? Browse other questions tagged python list or ask your own question .
- The Overflow Blog
- Where does Postgres fit in a world of GenAI and vector databases?
- Featured on Meta
- We've made changes to our Terms of Service & Privacy Policy - July 2024
- Bringing clarity to status tag usage on meta sites
- What does a new user need in a homepage experience on Stack Overflow?
- Feedback requested: How do you use tag hover descriptions for curating and do...
- Staging Ground Reviewer Motivation
Hot Network Questions
- Using "no" at the end of a statement instead of "isn't it"?
- Who was the "Dutch author", "Bumstone Bumstone"?
- Where to donate foreign-language academic books?
- Does the order of ingredients while cooking matter to an extent that it changes the overall taste of the food?
- Too many \setmathfont leads to "Too many symbol fonts declared" error
- Manifest Mind vs Shatter
- Story where character has "boomerdisc"
- How does the summoned monster know who is my enemy?
- How do I make a command that makes a comma-separated list where all the items are bold?
- Is there a faster way of expanding multiple polynomials with power?
- Do metal objects attract lightning?
- How can these humans cross the ocean(s) at the first possible chance?
- How much missing data is too much (part 2)? statistical power, effective sample size
- My visit is for two weeks but my host bought insurance for two months is it okay
- What explanations can be offered for the extreme see-sawing in Montana's senate race polling?
- Expected number of numbers that stay at their place after k swaps
- Historical U.S. political party "realignments"?
- How do we reconcile the story of the woman caught in adultery in John 8 and the man stoned for picking up sticks on Sabbath in Numbers 15?
- Parse Minecraft's VarInt
- Employee always seems distracted affecting others and his work, found out finally what it is, wondering if I can say something
- Is it possible to have a planet that's gaslike in some areas and rocky in others?
- How would you say a couple of letters (as in mail) if they're not necessarily letters?
- Integral concerning the floor function
- Which programming language/environment pioneered row-major array order?
Los Angeles Dodgers designate outfielder Jason Heyward for assignment
The Los Angeles Dodgers designated 15-year veteran outfielder Jason Heyward for assignment on Thursday.
The former All-Star, who turned 35 this month, is batting .208 with six homers and 28 RBI in 63 games in 2024.
Heyward is a career .257 hitter with 180 homers and 709 RBI in 1,766 games with the Atlanta Braves (2010-14), St. Louis Cardinals (2015), Chicago Cubs (2017-22) and Dodgers.
Atlanta drafted Heyward in the first round (14th overall) in 2007 and he made the National League All-Star team as a rookie in 2010. He won five Gold Gloves in right field (2012, 2014-17).
Heyward is playing this season on a one-year contract for $9 million. He has earned more than $210 million during his career.
The Dodgers filled the roster slot by activating infielder/outfielder Chris Taylor from the 10-day injured list. He has been out of the lineup since July 24 with a right groin strain.
Taylor, 33, is batting .167 with three homers and 15 RBI in 64 games with the Dodgers this season.
The USA TODAY app gets you to the heart of the news — fast. Download for award-winning coverage, crosswords, audio storytelling, the eNewspaper and more .
Cisco Security Advisory
Cisco nx-os software python sandbox escape vulnerabilities.
IMAGES
VIDEO
COMMENTS
The Python language has distinct concepts for expressions and statements. Assignment is a statement even if the syntax sometimes tricks you into thinking it's an expression (e.g. a=b=99 works but is a special syntax case and doesn't mean that the b=99 is an expression like it is for example in C). List comprehensions are instead expressions because they return a value, in a sense the loop they ...
Python's list is a flexible, versatile, powerful, and popular built-in data type. It allows you to create variable-length and mutable sequences of objects. In a list, you can store objects of any type. You can also mix objects of different types within the same list, although list elements often share the same type.
2. list[:] specifies a range within the list, in this case it defines the complete range of the list, i.e. the whole list and changes them. list=range(100), on the other hand, kind of wipes out the original contents of list and sets the new contents. But try the following:
Implicit Assignments in Python. Python implicitly runs assignments in many different contexts. In most cases, these implicit assignments are part of the language syntax. In other cases, they support specific behaviors. Whenever you complete an action in the following list, Python runs an implicit assignment for you: Define or call a function
Along with list comprehensions, we also use lambda functions to work with lists. While list comprehension is commonly used for filtering a list based on some conditions, lambda functions are commonly used with functions like map() and filter(). They are used for complex operations or when an anonymous function is required. Let's look at an example.
Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0. ... Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point ...
OUTPUT. x = 2 y = 4 4. Sequence assignment: In recent version of Python, tuple and list assignment have been generalized into instances of what we now call sequence assignment - any sequence of names can be assigned to any sequence of values, and Python assigns the items one at a time by position.
Data Structures — Python 3.12.5 documentation. 5. Data Structures ¶. This chapter describes some things you've learned about already in more detail, and adds some new things as well. 5.1. More on Lists ¶. The list data type has some more methods. Here are all of the methods of list objects:
Exercise 1: Reverse a list in Python. Exercise 2: Concatenate two lists index-wise. Exercise 3: Turn every item of a list into its square. Exercise 4: Concatenate two lists in the following order. Exercise 5: Iterate both lists simultaneously. Exercise 6: Remove empty strings from the list of strings.
In this tutorial, you used assignment expressions to make compact sections of Python code that assign values to variables inside of if statements, while loops, and list comprehensions. For more information on other assignment expressions, you can view PEP 572 —the document that initially proposed adding assignment expressions to Python.
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. Lists are created using square brackets:
Lists and tuples are arguably Python's most versatile, useful data types. You will find them in virtually every nontrivial Python program. Here's what you'll learn in this tutorial: You'll cover the important characteristics of lists and tuples. You'll learn how to define them and how to manipulate them.
Python lists store multiple data together in a single variable. In this tutorial, we will learn about Python lists (creating lists, changing list items, removing items, and other list operations) with the help of examples.
Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and separated by commas. The list is a sequence data type which is used to store the collection of data.
Python Lists Access List Items Change List Items Add List Items Remove List Items Loop Lists List Comprehension Sort Lists Copy Lists Join Lists List Methods List Exercises. ... Python Assignment Operators. Assignment operators are used to assign values to variables: Operator Example Same As
How to create a Python list. Let's start by creating a list: my_list = [1, 2, 3] empty_list = [] Lists contain regular Python objects, separated by commas and surrounded by brackets. The elements in a list can have any data type, and they can be mixed. You can even create a list of lists.
These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges. All exercises are tested on Python 3. Each exercise has 10-20 Questions. The solution is provided for every question. These Python programming exercises are suitable for all Python developers.
Lists are one of the most commonly used data structures in Python, providing a versatile way to store and manipulate collections of items. This tutorial is perfect for students, professionals, or anyone interested in enhancing their Python programming skills by learning about list methods and applying them through practical exercises.
I have Python 3.12 on Windows 10. I work with spreadsheets. I read each row one at a time, and grab one piece of data from that row, let's say a job number, which could be in column A, B or C. Yes, the spreadsheet is a mess, I can't change that. I have to work with what I'm given. But the preferred order I look for the job number in the columns is B, A, C. I need to look for a job in ...
These files contain the assignment answers for each respective week. Select the Week File: Click on the file corresponding to the week you are interested in. For example, if you need answers for Week 3, open the week-03.md file. Review the Answers: Each week-XX.md file provides detailed solutions and explanations for that week's assignments ...
For complete implementations around handling auto function calling in Python, please see our code samples here. As we continue bringing you new features in Semantic Kernel, we want to highlight that we are tracking an issue related adding support for OpenAI's structured outputs.
The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment. To actually copy the list, you have several options: You can use the built-in list.copy() method (available since Python 3.3): new_list = old_list.copy() You can slice it: new_list = old_list[:]
Center fielder Byron Buxton is "getting closer" and likely to get a rehab assignment when he's ready to return to the Twins lineup, manager Rocco Baldelli said ahead of Monday's game against ...
Tatis hasn't played since June 21 and was hitting .279 with 14 home runs and 36 RBIs when he went on the injured list. Even without Tatis, the Padres have maintained a National League Wild Card ...
The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression. Syntax: a := expression. Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop.
- C Andrew Knapp designated for assignment. — SFGiants (@SFGiants) August 29, 2024 The second-year catcher was placed on the 10-day IL dating back to Aug. 19 with a right oblique strain.
good question! the answer is simple: my 3 lists in one list were only an example. originally, i wanted to put 15 lists into a list. of course, your way is working, but it looks somewhat weird if i implement it that way. i just wanted to learn if there is an advanced way of doing this. but thanks ;) -
The Los Angeles Dodgers designated 15-year veteran outfielder Jason Heyward for assignment on Thursday. The former All-Star, who turned 35 this month, is batting .208 with six homers and 28 RBI in ...
Multiple vulnerabilities in the Python interpreter of Cisco NX-OS Software could allow an authenticated, low-privileged, local attacker to escape the Python sandbox and gain unauthorized access to the underlying operating system of the device. These vulnerabilities are due to insufficient validation of user-supplied input. An attacker could exploit these vulnerabilities by manipulating ...
Yoan Moncada, the frustrating infielder for the Chicago White Sox, is finally set to begin a rehab assignment next week. Per James Fegan, who covers the team: C