Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the differences between Python tuples and lists

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article editor for you detailed introduction of "Python tuple and list what are the differences", the content is detailed, the steps are clear, the details are handled properly, I hope this article "Python tuple and list what are the differences" article can help you solve doubts, following the editor's ideas slowly in depth, together to learn new knowledge.

What are tuples and lists in Python?

Tuples and lists are built-in data structures in Python. They are containers that allow you to organize data by storing an ordered collection of one or more items.

The class of tuple is "tuple".

The class of the list is list.

You can use the type () built-in function and pass the object as a parameter to test. This allows you to check whether it is a tuple or a list.

Suppose you create a tuple called my_tuple. You can check its type like this:

> type (my_tuple) # output

This is especially useful for debugging.

Now let's look at some other similarities between tuples and lists.

Similarities between tuples and lists in Python

As I mentioned earlier, tuples and lists are indeed similar, sharing some of the features we will introduce now.

Both tuples and lists can store multiple items under one variable

Tuples and lists can be empty or contain one or more items under a single variable.

The only difference is syntax: you can create tuples () by enclosing them with left and right brackets, while lists are represented and defined by left and right square brackets [].

To create an empty tuple, you can use the parenthesis (), or tuple () constructor method alone.

> type (()) > my_tuple = () > type (my_tuple) # or.. > my_tuple = tuple () > type (my_tuple)

To create an empty list, you can use two square brackets alone or call the list () constructor method.

> type ([]) > my_list = [] # or.. > my_list = list ()

When creating a tuple with an item, don't forget to add a comma at the end.

> age = (28,)

If you use this tuple () method to create a tuple, don't forget that it requires double parentheses.

> age = tuple ((28,)) > type (age)

If you do not add a trailing comma, Python will not create it as a tuple.

> age = (28) > type (age)

When creating a list of items, you don't have to worry about adding a comma after it.

> age = [28] > type (age)

Stored items are usually similar in nature and related to each other in some way.

You can create tuples or lists that contain only a sequence of strings, integers, or Boolean values, each of which is separated by a comma.

You can also create tuples or lists that contain a mix of different data types.

> my_information = ["Dionysia", 27False True, "Lemonaki", 7, "Python", False] # or.. > my_information = list (("Dionysia", 27False True, "Lemonaki", 7, "Python", False)) print (my_information) ['Dionysia', 27 Lemonaki', True,' Lemonaki', 7, 'Python', False]

Lists and tuples can contain duplicates, and values can be repeated multiple times.

> information = ("Jimmy", 50 Python True, "Kate", 50) > > print (information) ('Jimmy', 50 Kate', 50) or.. > my_information = ["Dionysia", 27 pr True, "Lemonaki", 7, "Python", False,27, "Python", 27]

If you forget the comma, you will get an error:

> information = ("Jimmy" 50 my_information, 50) File ", line 1 > information = (" Jimmy "50 Kate, 50) ^ SyntaxError: invalid syntax > my_information = [" Dionysia "28 Dionysia," Lemonaki ", 7," Python ", False] File", line 1 my_information = ["Dionysia" 28 true, "Lemonaki", 7, "Python", False] ^ SyntaxError invalid syntax

To check the length and determine how many items are in the tuple or list, use the len () method.

> my_information = ["Dionysia", 27 my_information True, "Lemonaki", 7, "Python", False,27, "Python", 27] > tuples and lists in len (my_information) 7Python support unpacking

In essence, when creating tuples or lists, as I mentioned earlier, many values are "packaged" into a variable.

Front_end = ("html", "css", "javascript")

These values can be "unpacked" and assigned to individual variables.

> front_end = ("html", "css", "javascript") > content,styling,interactivity = front_end > content'html' > styling'css' > interactivity'javascript'

Make sure that the variable you create is exactly the same as the number of values in the tuple / list, otherwise Python will throw an error:

> front_end = ("html", "css", "javascript") > content,styling = front_endTraceback (most recent call last): File ", line 1, in ValueError: too many values to unpack (expected 2) # or.. > front_end = (" html "," css "," javascript ") > > content,styling,interactivity,data = front_endTraceback (most recent call last): File", line 1, in ValueError: not enough values to unpack (expected 4, got 3) in Python You can access items through tuples and indexes in lists

As mentioned earlier, tuples and lists are ordered collections of projects.

The order is fixed and remains the same throughout the life cycle of the program.

The order of the specified items will remain the same from the time they are created.

Each value in a tuple and list has a unique identifier, also known as an index.

Therefore, you can access each item in the tuple and list by referencing the index.

Indexes in Python (and most programming languages and computer science in general) start at 0.

Therefore, the index of the first item is 0, the index of the second item is 1, and so on.

Write the name of the tuple or list in square brackets, and then the name of the index in square brackets.

> names = ("Jimmy", "Timmy", "John", "Kate") > names [2] 'John'

Or like this:

> programming_languages = ["Python", "JavaScript", "Java", "C"] > programming_languages [0] 'Python' > programming_languages [1]' JavaScript'

Well, now that we've seen the similarities, let's look at the differences between tuples and lists.

The difference between tuples and lists in Python is immutable, while lists are mutable in Python

Tuples are immutable in Python, which means that once you create a tuple, the items in it cannot be changed.

Tuples cannot be constantly changed.

If you try to change the value of one of the items, an error occurs:

> names = ("Jimmy", "Timmy", "John", "Kate") > names [2] = "Kelly" Traceback (most recent call last): File ", line 1, in TypeError: 'tuple' object does not support item assignment

Because tuples cannot be changed, you cannot add, replace, reassign, or delete any items.

This also means that the tuple has a fixed length. Their length will never change throughout the life cycle of the program.

When to use tuples

Tuples are ideal for use if you want the data in the collection to be read-only, never change, and always remain the same.

Because of this ability and the guarantee that the data will never change, tuples can be used in dictionaries and collections, which requires that the elements contained in them are immutable types.

When to use a list

On the other hand, you can easily change and modify the list because the list is variable.

This means that lists are variable-- you can add items to the list, remove items from the list, move items, and easily switch them in the list.

Lists are useful when you want your data to be flexible or not always the same and modify it when needed.

Lists support a variety of built-in Python methods that perform certain operations on lists that you cannot use on tuples.

This means that the length and size of the list grow and shrink throughout the life cycle of the program.

Now let's look at some simple ways to change the list.

How to update a list in Python

Because the list is variable, you need to know some basic ways to update the data in it.

How to update items in a list in Python

To update a single specific item in the list, reference its index number in square brackets and assign a new value to it.

# general syntax > list_ name [index] = new_value > programming_languages = ["Python", "JavaScript", "Java", "C"] > print (programming_languages) ['Python',' JavaScript', 'Java',' C'] > programming_languages [2] = "C++" > print (programming_languages) ['Python',' JavaScript', 'Category entries,' C'] how to add items to the list in Python

There are some built-in methods in Python to add items to the list.

The append () method adds a new item to the end of the list.

# general syntax > > list_name.append (item) > programming_languages = ["Python", "JavaScript", "Java", "C"] > print (programming_languages) ['Python',' JavaScript', 'Java',' C'] > > programming_languages.append ("C++") > print (programming_languages) ['Python',' JavaScript', 'Java',' Clearing, 'Clearing']

To add an item at a specific location, use the insert () method.

This inserts an item into the list at the given location. The remaining elements in the list after the item you want to add are pushed to the right.

# general syntax > > list_name.insert (index,item) > names = ["Cody", "Dillan", "James", "Nick"] > print (names) ['Cody',' Dillan', 'James',' Nick'] > names.insert (0, "Stephanie") > > print (names) ['Stephanie',' Cody', 'Dillan',' James', 'Nick']

If you want to add multiple items to the list, use the extend () method.

This adds an iterable object at the end of the list. For example, you can add a new list to the end of an existing list.

# general syntax > > list_name.extend (iterable) > programming_languages = ["Python", "JavaScript"] > more_programming_languages = ["Java", "C"] # add more_programming_languages to programming_languages > programming_languages.extend (more_programming_languages) > print (programming_languages) ['Python',' JavaScript', 'Java',' C'] how to delete items from the list in Python

There are two built-in methods in Python for removing items from the list.

One is the remove () method. This will delete the first instance of the project you specified.

# general syntax > > list_name.remove (item) > programming_languages = ["Python", "JavaScript", "Java", "C"] > > print (programming_languages) ['Python',' JavaScript', 'Java',' C'] > programming_languages.remove ("Java") > > print (programming_languages) ['Python',' JavaScript','C'] # deletes only first occurence > > programming_languages = ["Python", "JavaScript", "Java", "C" "Python"] > programming_languages.remove ("Python") > print (programming_languages) ['JavaScript',' Java', 'Clearing,' Python']

Another way is to use the pop () method.

No arguments are passed, and it deletes the last item in the list.

You can pass in the index of the specific item you want to delete as a parameter.

In both cases, the removed value is returned, which is useful. If desired, you can store it in a variable for later use.

> programming_languages = ["Python", "JavaScript", "Java", "C"] > programming_languages.pop ()'C'> print (programming_languages) ['Python',' JavaScript', 'Java'] # store returned value in a variable > programming_languages = ["Python", "JavaScript", "Java", "C"] > fave_language = programming_languages.pop (0) > > print (fave_language) Python reads here This article "what are the differences between Python tuples and lists" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report