Suppose we need to record the ages of 5 students. Instead of creating 5 separate variables, we can simply create a list: Show
Create a Python ListA list is created in Python by placing items inside 5, separated by commas . For example,
Here, we have created a list named numbers with 3 integer items. A list can have any number of items and they may be of different types (integer, float, string, etc.). For example,
Access Python List ElementsIn Python, each item in a list is associated with a number. The number is known as a list index. We can access elements of an array using the index number (0, 1, 2 …). For example,
In the above example, we have used the list comprehension to make a list with each item being increased by power of 2. Notice the code, 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. Upon completion you will receive a score so you can track your learning progress over time: Take the Quiz » Python ListsIn 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 ( 5), as shown below:>>>
The important characteristics of Python lists are as follows:
Each of these features is examined in more detail below. Remove adsLists Are OrderedA 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: >>>
Lists Can Contain Arbitrary ObjectsA 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: >>>
List Elements Can Be Accessed by IndexIndividual 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 6 are shown below:Here is Python code to access some elements of 6:>>>
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 6 is a list, the expression 9 returns the portion of 6 from index 1 to, but not including, index 2:>>> 0Other features of string slicing work analogously for list slicing as well:
Several Python operators and built-in functions can also be used with lists in ways that are analogous to strings:
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: >>> 0For that matter, you can do likewise with a string literal: >>> 1Remove adsLists Can Be NestedYou 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: >>> 2The object structure that 6 references is diagrammed below: 7, 8, and 9 are strings, each one character long:>>> 3But 00 and 01 are sublists:>>> 4To access the items in a sublist, simply append an additional index: >>> 5 02 is yet another sublist, so adding one more index accesses its elements:>>> 6There 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: >>> 7However, 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 6 using 3:>>> 8 6 has only five elements—three strings and two sublists. The individual elements in the sublists don’t count toward 6’s length.You’d encounter a similar situation when using the 9 operator:>>> 9 08 is not one of the elements in 6 or 00. It is only directly an element in the sublist 02. An individual element in a sublist does not count as an element of the parent list(s).Remove adsLists Are MutableMost 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 ValueA single value in a list can be replaced by indexing and simple assignment: >>> 0You may recall from the tutorial that you can’t do this with a string: >>> 1A list item can be deleted with the 12 command:>>> 2Modifying Multiple List ValuesWhat if you want to change several contiguous elements in a list at one time? Python allows this with , which has the following syntax: 3Again, for the moment, think of an iterable as a list. This assignment replaces the specified slice of 6 with 14:>>> 4The 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: >>> 5Note that this is not the same as replacing the single element with a list: >>> 6You can also insert elements into a list without removing anything. Simply specify a slice of the form 15 (a zero-length slice) at the desired index:>>> 7You 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 12 statement with the same slice:>>> 8Prepending or Appending Items to a ListAdditional items can be added to the start or end of a list using the 1 concatenation operator or the 18 :>>> 9Note 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: >>> 0Note: 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: >>> 1This 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 6 is a list of the characters in the string 20.If you really want to add just the single string 20 to the end of the list, you need to specify it as a singleton list:>>> 2If 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 ListFinally, 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: >>> 3List methods are different. Because lists are mutable, the list methods shown here modify the target list in place. 22
22 appends object 24 to the end of list 6:>>> 4Remember, list methods modify the target list in place. They do not return a new list: >>> 5Remember that when the 1 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:>>> 6The 27 method does not work that way! If an iterable is appended to a list with 27, it is added as a single object:>>> 7Thus, with 27, you can append a string as a single entity:>>> 8 30
Yes, this is probably what you think it is. 31 also adds to the end of a list, but the argument is expected to be an iterable. The items in 14 are added individually:>>> 9In other words, 31 behaves like the 1 operator. More precisely, since it modifies the list in place, it behaves like the 18 operator:>>> 0 36
36 inserts object 24 into list 6 at the specified 40. Following the method call, 41 is 24, and the remaining list elements are pushed to the right:>>> 1 43
43 removes object 24 from list 6. If 24 isn’t in 6, an exception is raised:>>> 2 49
This method differs from 50 in two ways:
51 simply removes the last item in the list:>>> 3If the optional 40 parameter is specified, the item at that index is removed and returned. 40 may be negative, as with string and list indexing:>>> 4 40 defaults to 55, so 56 is equivalent to 51.Remove adsLists Are DynamicThis 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: >>> 5Similarly, a list shrinks to accommodate the removal of items: >>> 6Python TuplesPython 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.” Defining and Using TuplesTuples are identical to lists in all respects, except for the following properties:
Here is a short example showing a tuple definition, indexing, and slicing: >>> 7Never fear! Our favorite string and list reversal mechanism works for tuples as well: >>> 8Note: 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: >>> 9Why use a tuple instead of a list?
In a Python REPL session, you can display the values of several objects simultaneously by entering them directly at the 60 prompt, separated by commas:>>> 0Python 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: >>> 1>>> 2But what happens when you try to define a tuple with one item: >>> 3Doh! Since parentheses are also used to define operator precedence in expressions, Python evaluates the expression 61 as simply the integer 62 and creates an 63 object. To tell Python that you really want to define a singleton tuple, include a trailing comma ( 64) just before the closing parenthesis:>>> 4You 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: >>> 5Remove adsTuple Assignment, Packing, and UnpackingAs you have already seen above, a literal tuple containing several items can be assigned to a single object: >>> 6When this occurs, it is as though the items in the tuple have been “packed” into the object: >>> 7If that “packed” object is subsequently assigned to a new tuple, the individual items are into the objects in the tuple: >>> 8When unpacking, the number of variables on the left must match the number of values in the tuple: >>> 9Packing and unpacking can be combined into one statement to make a compound assignment: >>> 0Again, the number of elements in the tuple on the left of the assignment must equal the number on the right: >>> 1In 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: >>> 2It 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: >>> 3In Python, the swap can be done with a single tuple assignment: >>> 4As 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. Remove adsConclusionThis 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! Take the Quiz: Test your knowledge with our interactive “Python Lists and Tuples” quiz. Upon completion you will receive a score so you can track your learning progress over time: Take the Quiz » « Strings in Python Dictionaries in Python » Mark as Completed 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 🐍 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. Send Me Python Tricks » About John Sturtz John is an avid Pythonista and a member of the Real Python tutorial team. » More about JohnEach 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: Aldren Dan Joanna 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: Level Up Your Python Skills » Master Real-World Python Skills Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » What Do You Think? Rate this article: Tweet Share Share EmailWhat’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. and get answers to common questions in our support portal. What is an object in a list?In category theory, an abstract branch of mathematics, and in its applications to logic and theoretical computer science, a list object is an abstract definition of a list, that is, a finite ordered sequence.
What are objects in Python?An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. Python is object-oriented programming language that stresses on objects i.e. it mainly emphasizes functions.
How many objects are in list Python?Using Len() function to Get the Number of Elements
We can use the len( ) function to return the number of elements present in the list.
|