Python list to кортеж

How to convert a list to a list of tuples?

I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary. This is the input list:

L = [1,term1, 3, term2, x, term3. z, termN] 
[(1, term1), (3, term2), (x, term3), . (z, termN)] 

7 Answers 7

>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] # Create an iterator >>> it = iter(L) # zip the iterator with itself >>> zip(it, it) [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')] 

You want to group three items at a time?

You want to group N items at a time?

# Create N copies of the same iterator it = [iter(L)] * N # Unpack the copies of the iterator, and pass them as parameters to zip >>> zip(*it) 

Could someone explain what zip is doing in this context? I thought I understood how it works but apparently not, since this doesn’t give [(1,1,1),(‘term1′,’term1′,’term1’). ]

@user1717828 every time you access the iterator it advances the position. Zip is pairing two things, taken from the same iterator here. If you wrote zip(iter(L), iter(L), iter(L)) it would do that, but by breaking out the iter creation and sharing it you get this behaviour.

Читайте также:  Menu making in css

This will work in python2, but in python3, you actually need to put the zip object in a list like so: list(zip(it,it)) as python3 does not evaluate the zip unless you explicitly ask for it — see stackoverflow.com/a/19777642

wow, at first didn’t understand what you did there, but now I’m amazed at how simple and beautiful your solution is

Try with the group clustering idiom:

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

Ok, I think I understood your code, It is same as @thefourtheye’s answer except you use * 2 to make two copies. I can also write is as zip(*(iter(L),) * 2) .

«The left-to-right evaluation order of the iterables is guaranteed» upvote for the explanation quote.. I finally get how this works despite using it many times!! each time the iterator is «evaluated» it is «advanced» to the next element. Thats how/why we get the next element as the second element of the tuple. It’s so obvious now!

List directly into a dictionary using zip to pair consecutive even and odd elements:

or, since you are familiar with the tuple -> dict direction:

d = dict(t for t in zip(m[::2], m[1::2])) 

Источник

Convert List to Tuple in Python

Python Certification Course: Master the essentials

There are multiple scenarios when we want a specific data type in our programs. Lists are mutable, but it is slow to iterate over them. On the other hand, the tuples are immutable , but it is much faster to iterate over the items in the tuple. Sometimes it is a good idea to use the properties and nature of the list, whereas, in a few scenarios, the properties and nature of tuples will help to optimize the program.

We can convert one data type into another between the execution to get the advantage of both data types in a single program.

How To Convert A List To A Tuple In Python?

Both lists and tuples have different natures and properties, which gives certain advantages in certain conditions. By converting one data type into another, we can take advantage of the properties and nature of both data structures. We can use the tuple constructor to convert the list to tuple , we can also use the for loop to iterate over each list item and add it one by one into a tuple, or make use of list unpacking inside parenthesis for conversion. All the methods above to convert the list to a tuple in python are explained below with a coding example.

Method — 1 : Using tuple builtin function

The following coding example shows how to use the built-in tuple function in python to convert the list into a tuple. This tuple function is also known as tuple constructor , which is used to construct or create the tuple in python.

As we can see in the above coding example, the first list is created with some random values, then converted to the tuple using the inbuilt tuple method as used on line number 6 . At the start and the end, we printed the type of myList and myTuple after conversion, which clearly shows that list got converted to the tuple.

Method — 2: Using loop inside the tuple

The following coding example shows how to convert the list to a tuple in python using a loop inside a tuple. Here we just added the for loop inside the inbuilt tuple function to iterate over the elements from the list.

As we can see, the above example is similar to method 1 . Still, the slight difference is that we added the for loop inside the tuple function to iterate over each element from the myList in the tuple function and add them inside the myTuple.

Method — 3 : Using list

The following coding example shows how to convert a list to a tuple in python with the help of list unpacking inside a parenthesis . This method is a little faster than others due to the efficient internal opcode sequence of list unpacking in python, but it is not good if readability is concerned.

As shown in the above coding example, we unpacked the list inside the parenthesis to convert it to a tuple in python. The list gets converted to a tuple due to the presence of ‘,’ in parenthesis. Here we used myList in which ‘*’ will unpack the myList, and because we used the ‘,’ after myList, all unpacked values converted to the tuple.

Conclusion

  • To utilize the properties and nature of both lists and tuples in a single program, we can convert one into another.
  • Inbuilt tuple() function, also known as a constructor function, can be used to convert a list to a tuple.
  • We can use for loop inside the tuple function to convert the list into a tuple.
  • It is faster to convert the list to a tuple in python by unpacking the list inside parenthesis.

Learn More

Источник

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

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

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

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

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

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

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

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

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

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

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

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

Источник

Convert list to tuple in Python [duplicate]

Not to be overly picky, but you probably also shouldn’t use lower case «el» as a variable name due to its resemblance to 1. Same goes for capital «oh» due to its resemblance to zero. Even «li» is much more readable in comparison.

@Tomerikoo unless there is a better canonical, perhaps it would be better to edit the question to be a pure how-to rather than dupe-hammering it to something that will be useless for most people who get here from a search engine. Although that would break the top answers somewhat. hmm.

@KarlKnechtel The accepted answer (and highly voted) is answering the dupe (i.e. the overriding mix-up rather than actually converting a list to a tuple). By the amount of votes, I assume that most people coming here will be just fine with the current dupe. As to the others coming here for the title — the answer is basically in the question. I’m not sure this problem justifies a SO question but that’s a different philoSOphical discussion

8 Answers 8

It should work fine. Don’t use tuple , list or other special names as a variable name. It’s probably what’s causing your problem.

>>> l = [4,5,6] >>> tuple(l) (4, 5, 6) >>> tuple = 'whoops' # Don't do this >>> tuple(l) TypeError: 'tuple' object is not callable 

This is retriving an extra value when there is only one element in the list >>> taskid = [«10030»] >>> t = tuple(l) >>> t (‘10030’,)

@Rafa, the comma is part of the tuple notation when there is only one element, if that’s what you mean.

Expanding on eumiro’s comment, normally tuple(l) will convert a list l into a tuple:

In [1]: l = [4,5,6] In [2]: tuple Out[2]: In [3]: tuple(l) Out[3]: (4, 5, 6) 

However, if you’ve redefined tuple to be a tuple rather than the type tuple :

In [4]: tuple = tuple(l) In [5]: tuple Out[5]: (4, 5, 6) 

then you get a TypeError since the tuple itself is not callable:

In [6]: tuple(l) TypeError: 'tuple' object is not callable 

You can recover the original definition for tuple by quitting and restarting your interpreter, or (thanks to @glglgl):

In [6]: del tuple In [7]: tuple Out[7]:

Convoluted trivia: even if tuple is shadowed, the actual type is still available as ().__class__ as in: ().__class__(range(10)) 🙂

To add another alternative to tuple(l) , as of Python >= 3.5 you can do:

short, a bit faster but probably suffers from readability.

This essentially unpacks the list l inside a tuple literal which is created due to the presence of the single comma , .

P.s: The error you are receiving is due to masking of the name tuple i.e you assigned to the name tuple somewhere e.g tuple = (1, 2, 3) .

Using del tuple you should be good to go.

You might have done something like this:

>>> tuple = 45, 34 # You used `tuple` as a variable here >>> tuple (45, 34) >>> l = [4, 5, 6] >>> tuple(l) # Will try to invoke the variable `tuple` rather than tuple type. Traceback (most recent call last): File "", line 1, in tuple(l) TypeError: 'tuple' object is not callable >>> >>> del tuple # You can delete the object tuple created earlier to make it work >>> tuple(l) (4, 5, 6) 

Here’s the problem. Since you have used a tuple variable to hold a tuple (45, 34) earlier. So, now tuple is an object of type tuple now.

It is no more a type and hence, it is no more Callable .

Never use any built-in types as your variable name. You do have any other name to use. Use any arbitrary name for your variable instead.

Источник

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