[Tutor] Dynamic naming of lists
Dave Angel
davea at davea.name
Tue Mar 31 16:30:04 CEST 2015
On 03/31/2015 10:00 AM, Ian D wrote:
> Hi
>
> I have a list that I am splitting into pairs of values. But the list is dynamic in size. It could have 4 values or 6 or more.
>
> I originally split the list into pairs, by using a new list and keep a pair in the old list by just popping 2 values. But if the list is longer than 4 values. I cannot do this. I can only envision I would need to dynamically create lists. How would I do this?
>
> while returned_list_of_items:
> for i in range(1):
> new_list.append(returned_list_of_items.pop(0)) #pop first value and append
> new_list.append(returned_list_of_items.pop(0)) #pop second value and append
>
It'd really be a lot clearer if you gave one or more examples of input
and output data. Like you want list [1,2,3,4] to become [ (1,2), (3,4) ]
I'll guess you want a list of two-tuples. It so happens there's a nice
built-in for the purpose.
https://docs.python.org/3/library/functions.html#zip
>>> s = [1,2,3,4,5,6,7,8]
>>> list(zip(*[iter(s)]*2))
[(1, 2), (3, 4), (5, 6), (7, 8)]
--
DaveA
More information about the Tutor
mailing list