Python make tuple from list

Как перевести список в кортеж в Python

Чтобы создать список в Python, используйте квадратные скобки([]). Чтобы создать кортеж, используйте круглые скобки(( )). Список имеет переменную длину, а кортеж имеет фиксированную длину. Следовательно, список может быть изменен, а кортеж — нет.

Преобразование списка в кортеж в Python

Чтобы перевести список Python в кортеж, используйте функцию tuple(). tuple() — это встроенная функция, которая передает список в качестве аргумента и возвращает кортеж. Элементы списка не изменятся при преобразовании в кортеж. Это самый простой способ преобразования.

Сначала создайте список и преобразуйте его в кортеж с помощью метода tuple().

В этом примере мы определили список и проверили его тип данных. Чтобы проверить тип данных в Python, используйте метод type(). Затем используйте метод tuple() и передайте список этому методу, и он вернет кортеж, содержащий все элементы списка.

Читайте также:  Импорт закладок html файл

Список Python в кортеж, используя (* list, )

Из версии Python 3.5 и выше вы можете сделать этот простой подход, который создаст преобразование из списка в кортеж(*list, ).(*list, ) распаковывает список внутри литерала кортежа, созданного из-за наличия одиночной запятой(, ).

Вы можете видеть, что(*mando, ) возвращает кортеж, содержащий все элементы списка. Никогда не используйте имена переменных, такие как tuple, list, dictionary или set, чтобы улучшить читаемость кода. Иногда это будет создавать путаницу. Не используйте зарезервированные ключевые слова при присвоении имени переменной.

В Python 2.x, если вы по ошибке переопределили кортеж как кортеж, а не как кортеж типа, вы получите следующую ошибку:

TypeError: объект ‘tuple’ не вызывается.

Но если вы используете Python 3.x или последнюю версию, вы не получите никаких ошибок.

Источник

3 Ways to Convert List to Tuple in Python

3 Ways to Convert List to Tuple in Python

There may be times when you wish to have a specific type of a variable during programming. Typecasting is a process used to change the variables declared in a specific data type into a different data type to match the operation performed by the code snippet. Python is an object-oriented language that consists of many data types. Today, we will learn List and Tuple data type in python and some methods to convert python list to a tuple in detail.

What is a List in Python?

Python lists are a data structure similar to dynamically sized arrays. The most important feature of python’s list is that it need not be homogeneous always. A list can contain elements like integers, strings, and also objects. Therefore, a python list is an ordered and changeable collection of data objects, unlike an array containing a single type of data.

The list is the most versatile and frequently used data structure in python. You can create a list by placing all the elements inside the square brackets([]) separated by commas. All these elements can be further accessed by the index number inside the square brackets, just like arrays. Remember that in the list data structure, indexing begins from zero(0), which means the first element of the list will be accessed with 0 inside the square brackets. Also, the list is mutable. That means you can add, update or remove elements of the list after it has been created. Below example shows the python list in detail:

For Example

list1 = ["favtutor", 1, 2.30] print(list1)

What is Tuple in Python?

Tuples in Python are a data structure used to store multiple elements in a single variable. Just like list data structure, a tuple is homogenous. Therefore, a tuple can consist of elements of multiple data types at the same time. You can create a tuple by placing all elements inside the parentheses(()) separated by commas. Note that the parentheses are an option, however, it is always a good practice to use them while working with tuples in python.

Unlike list data structure, a tuple is immutable. Hence, you cannot add, update or delete the elements of the tuple after creating it. However, if you want to perform any operations on the tuple, a separate copy of the same tuple is created, and then necessary modifications are made. Below example shows a tuple in python programming:

For Example

tuple1 = ("favtutor", 1, 2.3) print(tuple1) # Creating a tuple having one element tuple2 = ("favtutor",) print(type(tuple2))

Output

As shown in the above example, when you declare a tuple with a single element, it will be similar to the string class. Therefore, to avoid this issue, a single comma is placed after declaring a single string to identify the tuple class.

Difference between List and Tuple

Operations are performed better

Elements can be accessed faster

Consists of various built-in methods

Do not consist of any built-in methods

Iterations are time-consuming in list

Iterations are faster in the tuple

Convert List to Tuple in Python

As discussed above, the programming requires many operations to be performed on the data. Because the properties and nature of every data structure differ from one another, you have to convert the variable from one data type to another at some point. Similarly, below we have mentioned three common and most widely used methods to convert lists to a tuple in python programming.

1) Using tuple() builtin function

Python language consists of various built-in functions to ease your programming and the tuple() function is one of them. tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output. Check out the example below for converting “sample_list” into a tuple for better understanding.

For Example

sample_list = ['Compile', 'With', 'Favtutor'] #convert list into tuple tuple1 = tuple(sample_list) print(tuple1) print(type(tuple1))

Here, if you notice, we have used the type() function to identify the variable type that returns tuple object as an output.

2) Using loop inside the tuple

This method is a small variation of the above-given approach. You can use a loop inside the built-in function tuple() to convert a python list into a tuple object. However, it is the least used method for type conversion in comparison to others. Take a look at the below example to understand it in detail:

For Example

sample_list = ['Compile', 'With', 'Favtutor'] tuple1 = tuple(i for i in sample_list) print(tuple1)

3) Unpack list inside the parenthesis

To convert a list to a tuple in python programming, you can unpack the list elements inside the parenthesis. Here, the list essentially unpacks the elements inside the tuple literal, which is created by the presence of a single comma(,). However, this method is faster in comparison to others, but it suffers from readability which is not efficient enough.

For Example

sample_list = ['Compile', 'With', 'Favtutor'] #unpack list items and form tuple tuple1 = (*sample_list,) print(tuple1) print(type(tuple1))

Conclusion

Even though List and Tuple are different data structures in python, it is important to get familiar with their similarities and differences for using them while programming. This article helps you to understand the list and tuple in detail, along with their differences and some common methods to convert python list to tuple. If you wish to study more about type casting in python, check out our article on 6 ways to convert string to float.

Источник

How to Convert List to Tuple in Python

Here are the ways to convert a list to a tuple in Python:

Method 1: Using the tuple() function

The tuple() is a built-in function that accepts the list as an argument and returns the tuple. The list elements will not change when it converts into a tuple.

Example

mando = ["Mandalorian", "Grogu", "Ahsoka Tano", "Bo Katan", "Boba Fett"] print(mando) print(type(mando)) mando_tuple = tuple(mando) print(mando_tuple) print(type(mando_tuple))
['Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett'] ('Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett') 

Method 2: Using the (*list, )

From Python >= 3.5, you can make this easy approach that will create a conversion from the list to a tuple is (*list, ). The (*list, ) unpacks the list inside a tuple literal, created due to the single comma’s presence (, ).

Example

mando = ["Mandalorian", "Grogu", "Ahsoka Tano", "Bo Katan", "Boba Fett"] print(mando) print(type(mando)) mando_tuple = (*mando, ) print(mando_tuple) print(type(mando_tuple))
['Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett'] ('Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett') 

TypeError: ‘tuple’ object is not callable

But, if you use Python 3.x or the latest version, you will not get any errors.

mando = ("Mandalorian", "Grogu", "Ahsoka Tano", "Bo Katan", "Boba Fett") print(mando) mando_tuple = tuple(mando) print(mando_tuple)
('Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett') ('Mandalorian', 'Grogu', 'Ahsoka Tano', 'Bo Katan', 'Boba Fett')

Method 3: Using map() and lambda function

The map() function and lambda convert a list of integers to a list of strings and then use the join() method to concatenate the strings in the list with a comma separator.

Example

my_list = [1, 2, 3, 4, 5] my_tuple = tuple(map(lambda x: x, my_list)) print(my_tuple) 

Method 4: Using a custom function

def convert_list_to_tuple(lst): tup = () for element in lst: tup += (element,) return tup main_list = [11, 21, 19, 46] main_tuple = convert_list_to_tuple(main_list) print(main_tuple)

Источник

How to convert a list into a tuple in Python?

List and Tuple in Python are the class of data structure. The list is dynamic, whereas the tuple has static characteristics. We will understand list and tuple individually first and then understand how to convert a list into a tuple.

List

Lists are a popular and widely used data structures provided by Python. A List is a data structure in python that is mutable and has an ordered sequence of elements. Following is a list of integer values −

If you execute the above snippet, it produces the following output −

Tuple

A tuple is a collection of python objects that are separated by commas which are ordered and immutable. Immutable implies that the tuple objects once created cannot be altered. Tuples are sequences, just like lists. The differences between tuples and lists are, that tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

tup=('tutorials', 'point', 2022,True) print(tup)

If you execute the above snippet, produces the following output −

('tutorials', 'point', 2022, True)

In this article, we convert a list into a tuple by using a few methods. Each of these methods are discussed below.

Using the tuple() built-in function

An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.

Example 1

In the following code, we convert a list to a tuple using the tuple() built-in function.

list_names=['Meredith', 'Kristen', 'Wright', 'Franklin'] tuple_names= tuple(list_names) print(tuple_names) print(type(tuple_names))

Output

(‘Meredith’, ‘Kristen’, ‘Wright’, ‘Franklin’)

Example 2

Following is an another example of this −

my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple)

Output

This will give the output −

Using a loop

This method is similar to the above one, but in this case, we do not send the complete list as an argument whereas we retrieve each element from the list using a for loop to send it as an argument for the tuple() built-in function.

Example

The following is an example code to convert a list to a tuple using a loop.

list_names=['Meredith', 'Kristen', 'Wright', 'Franklin'] tuple_names= tuple(i for i in list_names) print(tuple_names) print(type(tuple_names))

Output

(‘Meredith’, ‘Kristen’, ‘Wright’, ‘Franklin’)

Using unpack list inside the parenthesis(*list, )

This method is faster when compared to others, but it is not efficient and difficult to understand. Inside the parenthesis, you can unpack the list elements. The list just unpacks the elements within the tuple literal, which is generated by a single comma (,).

In this example code, we use the unpacking method to convert a list to a tuple.

list_names=['Meredith', 'Kristen', 'Wright', 'Franklin'] tuple_names= (*list_names,) print(tuple_names) print(type(tuple_names))

Output

(‘Meredith’, ‘Kristen’, ‘Wright’, ‘Franklin’)

Источник

Оцените статью